8.3 string流

string流

头文件类型
sstreamistringstream,wistringstream 从string中读数据
ostringstream,wostringstream 从string中写数据
stringstream,wstringstream 读写string

string流操作

函数及类型含义
sstream fstrm创建未绑定string流
sstream fstrm(s)创建string流并绑定s
fstrm.str()返回strm保存的string拷贝
fstrm.str(s)将s拷贝到strm中,返回void。

样例:

bool valid(const string &num) {
	//位数判断、是否是数字等
	for (const auto s : num) {
		if(!isdigit(s))
		{
			return false;
		}
	}
	return true;
}
struct PersonInfo {
	string name;
	vector<string> phones;
};

int main() {
	string line, word;
	vector<PersonInfo> people;
	//使用istringstream
	while (getline(cin, line)) {
		PersonInfo info;
		istringstream record(line);
		record >> info.name;
		while (record >> word)
			info.phones.push_back(word);
		people.push_back(info);
	}
	//使用ostringstream
	//主要理解一个流的概念,就很好理解了,实际上就是通过类进行构造一个个流。
	for (const auto& entry : people) {
		ostringstream formatted, badNums;
		for (const auto& nums : entry.phones) {
			if (!valid(nums)) {
				badNums << " " << nums;
			}
			else {
				formatted << " " << nums;
			}
		}
		if (badNums.str().empty()) {
			cout << entry.name << ":" << formatted.str() << endl;
		}
		else {
			cerr << "error in "<<entry.name << ":" << badNums.str() << endl;
		}
	}
	return 0;
}

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值