我在C ++ Primer中做了一个练习,它说我需要在循环外定义std::istringstream record;
所以当我测试它时我会这样做第一个输出没问题但是第二个,第三个
似乎它没有在info.name
和word
存储任何值这里的代码
#include <iostream>
#include <vector>
#include <sstream>
struct PersonInfo {
std::string name;
std::vector <std::string> phones;
};
int main()
{
std::string line, word;
std::vector <PersonInfo> people;
std::istringstream record;
while (std::getline (std::cin, line)) {
PersonInfo info;
record.str(line);
record >> info.name;
std::cout << info.name << std::endl;
while (record >> word) {
info.phones.push_back (word);
std::cout << word << std::endl;
}
people.push_back (info);
}
for (unsigned i = 0; i != people.size(); ++i) {
std::cout << people[i].name << " ";
for (unsigned z = 0; z != people[i].phones.size(); ++z) {
std::cout << people[i].phones[z] << " ";
}
std::cout << std::endl;
}
return 0;
}
但是当我在外部循环中定义std::istringstream record;
时似乎没问题。
答案 0 :(得分:0)
那是因为它达到了EOF。源材料是错误的,或者说是record.clear()
以清除错误标记,并且您没有正确遵循说明。