//定义数据结构
struct PersonInfo{
std::string name;
std::vector<std::string> svec;
};
//输出函数
std::ostream & output(std::ostream &os, const PersonInfo &personInfo)
{
os << "###" << personInfo.name<<"@@@";
for (auto e : personInfo.svec)
{
os << "\t" << e;
}
return os;
}
string inputfile("in.txt");
vector<PersonInfo>pvec;
std::ifstream in(inputfile);
if (in)
{
string str,phone;
//1
//2
while (std::getline(in,str))
{
PersonInfo tmpInfo; // 1
std::istringstream strm;// 2
strm.str(str);
strm >> tmpInfo.name;
while (strm >> phone) //while结束会使流strm变无效;
{
tmpInfo.svec.push_back(phone); // 3
}
pvec.push_back(tmpInfo);
}
}
for (auto e : pvec)
{
output(cout, e) << endl;
}
读入数据:
运行结果:
分析编写时遇到的错误:
1.如果把标号为1的语句写在while的外面,则会出现如下图的结果:
原因:标号为3的语句为向一个容器中添加string元素,tmpInfo的作用域在while外,故其每次循环不会被销毁,每次向容器的尾端添加string元素(只因是容器可以无限添加);
2.如果把标号为2的语句写在while的外面,则会出现如下图的结果:
原因:流strm其作用域在while外,每次循环,其不被销毁,因为strm第一次while里面运行时,因为内层的while结束时,使流strm变为无效状态(参考流的条件状态),故无法再次将str拷贝给流strm;