sstream strm; | strm是一个未绑定的stringstream对象.sstream是头文件sstream中定义的一个类型. |
sstream strm(s); | strm是一个sstream对象,保存string s的一个拷贝。此构造函数是explicit的. |
strm.str() | 返回str所保存的string的拷贝 |
strm.str(s) | 将string s拷贝到strm中,返回void |
morgan 201552368 862550123
drew 9735550130
lee 6095550132 2015550175 8005550000struct PersonInfo
{
string name;
vector<string> phones;
} string line, word; //分别保存来自输入的一行和单词
vector<PersonInfo> people;//保存来自输入的所有记录
//逐行从输入读取数据,直至cin遇到文件尾(或其他错误)
while (getline(cin, line)&&line!="over")
{
PersonInfo info;//创建一个保存此记录数据的对象
istringstream record(line);// 将记录绑定到刚读入的行
record >> info.name;//读取名字---遇到空格结束输入
while (record >> word)//读取电话号码
{
info.phones.push_back(word);
}
people.push_back(info); //将此记录追加到people末尾
}
for (int i = 0; i < people.size(); i++)
for(int j=0;j<people[i].phones.size();++j)
cout << people[i].name << " " << people[i].phones[j] << endl;
record>>info.name是从一个string而不是标准输入读取数据。当string中的数据全部读出后while (record >> word),同样会触发"文件结束"信号,在record上的下一个输入操作会失败 string line, word; //分别保存来自输入的一行和单词
vector<PersonInfo> people;//保存来自输入的所有记录
//逐行从输入读取数据,直至cin遇到文件尾(或其他错误)
while (getline(cin, line)&&line!="over")
{
PersonInfo info;//创建一个保存此记录数据的对象
istringstream record(line);// 将记录绑定到刚读入的行
record >> info.name;//读取名字---遇到空格结束输入
while (record >> word)//读取电话号码
{
info.phones.push_back(word);
}
people.push_back(info); //将此记录追加到people末尾
}
for (const auto& entry : people)
{
ostringstream formatted, badnums;
for (const auto& nums : entry.phones)
{
if (!vaild(nums))
{
badnums << " " << nums;
}
else
{
formatted << " " << nums;
}
if (badnums.str().empty())
cout << entry.name << formatted.str() << endl;
else
cout <<"错误信息: "<< entry.name << badnums.str() << endl;
}
}