istringstream没有输出正确的数据

时间:2013-12-12 07:23:33

标签: c++ istringstream

我无法让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

1 个答案:

答案 0 :(得分: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
    }
}