【问题标题】:Stringstream is not recognized in while loop [closed]在while循环中无法识别Stringstream [关闭]
【发布时间】:2014-02-16 05:26:37
【问题描述】:

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 的第二个循环无法识别。

【问题讨论】:

  • 你的程序做什么infile 在哪里定义?你打开文件了吗?
  • 是的,它已定义。 set1 导入就好了。 set2 没有。
  • 如果您已经解决了之前的问题,请更新代码以反映这一点,因为保留旧代码并在没有任何证据的情况下引用更正且有效的更新是非常令人困惑的。另外,set1set2 是什么?我知道它们是布景,但它们的目的是什么?
  • @jrd1 实际上,没有。代码不应该更新,所以不是原型网站。根据您的回答,此问题应标记为已回答,并且应针对新问题打开一个新问题。这也将帮助 OP 将他的问题简化为更小的问题,这可能有助于他自己解决问题。恕我直言。

标签: c++ file getline stringstream file-io


【解决方案1】:

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

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.
}

【讨论】:

  • 感谢您的回复,但它仍然只读取一行。 while (std::getline(infile, line)) { while(iss >> input) { set1.insert(input); } }
  • @HaakonSjøgren:正确:因为这就是您在代码中所做的。如果我错了,请纠正我,但你原来的问题是你只能读一行。您现在遇到了一个新的不相关问题 - 与您在原始帖子中未解决的代码的其他方面相关。请编辑您的帖子以反映这一点。
  • @HaakonSjøgren:已编辑。
  • 我不希望输出字符串,我希望将输入字符串流转换为整数。
  • 我再次编辑了它。谢谢。
猜你喜欢
  • 2017-03-27
  • 1970-01-01
  • 2018-09-07
  • 1970-01-01
  • 2014-03-16
  • 1970-01-01
  • 2020-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多