ifstream 变量没有读取正确的字符 1

ifstream variable not reading correct character 1

我对以下代码片段有疑问。

我有一个用字符数组 FileName 引用的文件。该文件基本上可以是任何东西,但在我的例子中,它是一个文件,它在第一行包含一些不相关的文本,然后在一种情况下以 1(一)开头,在许多其他情况下以 0(零)开头。所以,我的文件是这样的:

iewbFLUW 82494HJF VROIREBURV.TEXT

0 TEST whatever something
0 TEST words and more
1 TEST something something
0 TEST oefeowif
...

我的代码片段的目的是选择用 1(一)选择的行。

// the stream object for my file:
string FileName = "myFile.text";
ifstream input(FileName);

// parsing the first line
char comment[1000];
input.getline(comment, 1000, '\n');
cout << comment << endl;

// parsing the other lines
bool select=false;
while (!input.eof())
{
    input >> select;

    cout << select << endl;
    if(select){
    // do something
     }
}

然而,虽然 FileName 以 0(零)开始第二行,但变量 selectinput >> select; [=16] 行之后的值为 1 =]

怎么会这样?

您的代码的主要问题是 input >> select 没有读取整行 ,而是在第一个空格处停止。然后你再次阅读你认为是下一行的 bool ,但实际上是该行第一个单词的下一个字符,所以你的流以 failbit 集结束,并且之后游戏结束,您无法再次从流中成功读取。

改为读取整行并使用 std::stringstream 来解析它,例如

#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;

int main(void)
{
    string FileName = "test.txt";
    ifstream input(FileName);

    // parsing the first line
    std::string line;
    getline(input, line); // ignore first line
    bool select = false;
    while (getline(input, line)) // read line by line
    {
        std::istringstream ss(line); // map back to a stringstream
        ss >> select; // extract the bool
        if (select) { // process the line (or the remaining stringstream)
            cout << line; // display the line if it select == true
        }
    }
}

如评论中所述,while(!input.eof())几乎总是错误的,请参阅Why is iostream::eof inside a loop condition considered wrong?