在循环外定义 std::istringstream 记录
defining std::istringstream record outside the loop
我在 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;
时,它似乎没问题。
那是因为它到达了 EOF。来源 material 有误,或者它要求 record.clear()
清除错误标志,而您没有正确按照说明进行操作。
我在 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;
时,它似乎没问题。
那是因为它到达了 EOF。来源 material 有误,或者它要求 record.clear()
清除错误标志,而您没有正确按照说明进行操作。