while循环中无法识别字符串流



Set2 while循环由于某种原因没有填充。Set1运行良好。

std::stringstream ss;
std::string line;
std::getline(infile, line);
ss.str(line);
int input;
// Populate set1
while(ss >> input)
{
set1.insert(input);
std::cout << "Populate set1 with " << input << "t pos is " << set1.getUsed() << std::endl;
}
// Populate set2
std::getline(infile, line);
ss.str(line);
std::cout << "n2nd getline verification: " << line << std::endl;
while (ss >> input)
{
set2.insert(input);
std::cout << "Populate set2 with " << input << "t pos is " << set2.getUsed() << std::endl;
}

它只填充set1而不填充set2。谢谢你的帮助。

编辑:现在读getline,谢谢。但是它没有将"line"中的值输入到ss字符串流,因此出于某种原因,set2的第二个循环无法识别。

这并不奇怪,因为您只读过一次-根本没有在流上循环。您的代码应该是:

std::string line
while(std::getline(infile, line)) {
std::cout << line << std::endl;//see what's in the line
//other code here...
}

为什么?因为您希望继续从流中读取(直到遇到EOF)。换句话说:您希望继续从流中读取,而您可以从流infile中获得一行数据。

更新:

OP的问题现在与上述问题有所不同。

例如,如果您的数据文件如下所示:

123 2978 09809 908098 
198 8796 89791 128797

你可以这样读数字:

std::string line
while(std::getline(infile, line)) {
//you line is populated
istringstream iss(line);
int num;
while (!(iss >> num).fail()) {
//save the number
}
//at this point you've reached the end of one line.
}

最新更新