练习17.21 使用本节中定义的valid函数重写8.3.2节(第289页)中的电话号码程序。


练习17.21 使用本节中定义的valid函数重写8.3.2节(第289页)中的电话号码程序。

解答: 主要就是写valid 来进行电话号码的正则表达式匹配。


#include <iostream>  
#include <fstream>  
#include <sstream>  
#include <string>  
#include <vector>  
#include <regex>

using namespace std;
using std::ifstream;
using std::ofstream;
using std::istringstream;
using std::ostringstream;
using std::string;
using std::vector;

struct PersonInfo {
	string name;
	vector<string> phones;
};

string format(const string &s) { return s; }

bool valid(const string &str)
{
	string patten = "(\\()?(\\d{4})?(\\d{3})?([-. ]*)?(\\))?(\\d{8})?(\\d{7})";
	regex r(patten);
	smatch m;
	regex_search(str, m, r);

	if (m[1].matched) {
		return m[4].matched && (m[2].matched || m[3].matched);
	}
	else {
		return !m[4].matched && (!m[2].matched && !m[3].matched);
	}
}

int main(int argc, char *argv[])
{
	string line, word;
	vector<PersonInfo> people;
	istringstream record;
/**
	if (argc != 2) {
		cerr << "Please give the file name." << endl;
		return -1;
	}
	ifstream in(argv[1]);
	if (!in)
	{
		cerr << "can't open input file" << endl;
		return -1;
	}
*/
	ifstream in("person_data.txt");
	ofstream out("person_data_save2.txt");

	while (getline(in, line)) {
		PersonInfo info;
		record.clear();
		record.str(line);
		record >> info.name;
		while (record >> word)
			info.phones.push_back(word);

		people.push_back(info);

	}

	ostringstream os;
	for (const auto &entry : people) {
		ostringstream formatted, badNums;
		for (const auto &nums : entry.phones) {
			if (!valid(nums)) {
				badNums << " " << nums;
			}
			else
				formatted << " " << format(nums);
		}
		if (badNums.str().empty())
		{
			cout << endl;
			os << "Formatted input: " << entry.name << " " << formatted.str() << endl;
		}
		else
			cerr << "input error: " << entry.name << " invalid number(s) " << badNums.str() << endl;
	}
	cout << os.str() << endl;

	return 0;
}

结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值