【问题标题】:istringstream not outputting correct dataistringstream 没有输出正确的数据
【发布时间】:2013-12-12 07:23:33
【问题描述】:

我无法让 istringstream 在下面显示的 while 循环中继续。数据文件也如下所示。我使用输入文件中的 getline 来获取第一行并将其放入 istringstream lineStream 中。它通过一次while循环,然后读取第二行并返回到循环的开头并退出而不是继续循环。我不知道为什么,如果有人可以提供帮助,我将不胜感激。 编辑:我有这个 while 循环条件的原因是因为文件可能包含错误数据行。因此,我想确保我正在读取的行在数据文件中具有如下所示的正确格式。

while(lineStream >> id >> safety){//keeps scanning in xsections until there is no more xsection IDs

    while(lineStream >> concname){//scan in name of xsection
        xname = xname + " " +concname;
    }


    getline(InputFile, inputline);//go to next xsection line
    if(InputFile.good()){
        //make inputline into istringstream
        istringstream lineStream(inputline);
        if(lineStream.fail()){
            return false;
        }
    }
}

数据文件

4   0.2  speedway and mountain
7   0.4 mountain and lee
6   0.5 mountain and santa

【问题讨论】:

  • 我认为您有太多令人困惑的文件读取操作,可能彼此不一致。
  • lineStream 需要声明在顶部/全局,而不是底部,否则它只会在位于的块中可用
  • 这有什么令人困惑的地方?
  • 这应该如何工作?为什么你在最后而不是在开始时制作 istringstream?为什么 fail() 除了构造(必须成功)之外没有执行任何操作时返回 true?
  • 最后是因为我想确保我正在读取这种特定类型的数据,而不是错误的数据。我将编辑原始帖子。 'fail()' 不返回 true。它跳过这个并进入while循环的检查然后退出。

标签: c++ istringstream


【解决方案1】:

在呈现的代码中,...

while(lineStream >> id >> safety){//keeps scanning in xsections until there is no more xsection IDs

    while(lineStream >> concname){//scan in name of xsection
        xname = xname + " " +concname;
    }

    getline(InputFile, inputline);//go to next xsection line
    if(InputFile.good()){
        //make inputline into istringstream
        istringstream lineStream(inputline);
        if(lineStream.fail()){
            return false;
        }
    }
}

lineStream 的内部声明声明了一个本地对象,当执行超出该块时,该对象不再存在,并且不会影响外部循环中使用的流。


一种可能的解决方法是稍微反转代码,如下所示:

while( getline(InputFile, inputline) )
{
    istringstream lineStream(inputline);

    if(lineStream >> id >> safety)
    {
        while(lineStream >> concname)
        {
            xname = xname + " " +concname;
        }
        // Do something with the collected info for this line
    }
}

【讨论】:

  • 不,我在原始评论中声明:“我使用输入文件中的 getline 获取第一行并将其放入 istringstream lineStream 中。它通过一次 while 循环......”这意味着我在整个循环之外声明了 lineStream,然后把它放在那里。除非你指的是 "if(InputFile.good()){} 中的内部声明 编辑:我明白你的意思。我会试试看。
  • 不知道怎么解释更清楚,不好意思。然后我唯一的额外建议是尝试在你的脑海中执行你当前的代码,就像计算机一样机械地一步一步地完成它,这样你就可以说服自己上面的解释是有意义和正确的。
  • 对不起,我在看到您的编辑后编辑了我的原始评论。我已经用调试器机械地完成了它,我正在尝试你的方法。
  • 我编辑了一些。第一次将原始while 更改为if 不会影响执行,只会影响代码的清晰度。二是把收集到的信息做事的评论移到更合适的地方。 :-)
  • 谢谢,现在可以使用了!不过我只是想知道,为什么 istringstream 在最后和下一次迭代中不保持其值?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-12
相关资源
最近更新 更多