ifstream变量未读取正确的字符1

时间:2015-06-01 20:16:04

标签: c++ boolean ifstream

我遇到以下代码段的问题。

我有一个字符数组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(零)开始第二行,但变量select在行input >> select;

后面的值为1

这怎么可能?

1 个答案:

答案 0 :(得分:0)

您的代码的主要问题是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?