练习8.11 本节的程序在外层while循环中定义了istringstream 对象。如果record 对象定义在循环之外,你需要对程序进行怎样的修改?重写程序,将record的定义移到while 循环之外,验证你设想的修改方法是否正确。
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
struct PersonInfo
{
string name;
vector<string> phones;
};
int main(int argc, char **argv)
{
string line, word;
vector<PersonInfo> people;
istringstream record;
while (getline(cin, line)) {
PersonInfo info;
record.clear();
record.str(line);
record >> info.name;
while (record >> word)
info.phones.push_back(word);
people.push_back(info);
}
for (auto item : people) {
cout << item.name << ends;
for (auto num : item.phones) {
cout << num << ends;
}
cout << endl;
}
return 0;
}
练习8.12 我们为什么没有在PersonInfo中使用类内初始化?
因为此处我们使用聚合类即可,不需要类内初始值。
练习8.13 重写本节的电话号码程序,从一个命名文件而非cin读取数据。
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
struct PersonInfo
{
string name;
vector<string> phones;
};
int main(int argc, char **argv)
{
string line, word;
vector<PersonInfo> people;
string file("123.txt");
ifstream fin(file);
istringstream record;
while (getline(fin, line)) {
PersonInfo info;
record.clear();
record.str(line);
record >> info.name;
while (record >> word)
info.phones.push_back(word);
people.push_back(info);
}
for (auto item : people) {
cout << item.name << ends;
for (auto num : item.phones) {
cout << num << ends;
}
cout << endl;
}
system("pause");
return 0;
}
/*
mogan 123 321
drew 222
ddd 555 666 777
*/
练习8.14 我们为什么将entry和nums定义为 const auto& ?
遍历字符串容器时,用引用可以节省拷贝时间和空间。
定义为const,保证在使用过程中不会更改其值。
本文详细解析了一个C++电话簿程序,展示了如何从输入流读取数据,并使用istringstream对象处理每一行输入,提取姓名和电话号码。通过将数据存储在PersonInfo结构体和vector容器中,实现了对个人联系信息的有效管理和输出。
4881

被折叠的 条评论
为什么被折叠?



