首页 > C++ primer 习题8.9的问题

C++ primer 习题8.9的问题

一切都进行的很顺利,就是在输出的时候,总是读取数据错误,即infile.fail()总是为true。但是不进行这个状态检查的话,从文件中读取的数据都是正确的。不知道哪里有问题,能使程序最后打印出读取的内容。

#include <iostream>
#include <vector>
#include <fstream>
#include <string>


using namespace std;

#define N 100

int main(void)
{
    vector<string> lines;
    string filename("out.txt");
    ifstream infile;
    infile.open(filename.c_str()); // open file
    if (!infile)
    {   
        cout << "error: can not open file: " << filename << endl;
        return -1;
    }
    string s;
    while (getline(infile, s))
    {
        cout << "s: " << s << endl;
        lines.push_back(s);
    }
    infile.close();
    if (infile.bad()) // 发生系统故障
        cout << "error: system failure" << endl;
    else if (infile.fail())  // 读入数据失败
        cout << "error : read failure " << endl;
    else
    {
        cout << "vector: " << endl;
        for (vector<string>::iterator iter = lines.begin(); iter != lines.end(); iter++)
            cout << *iter << endl;
    }

    system("pause");
    return 0;
}

在文件遇到 eof 的时候 ifstream::fail() 会返回 true,所以你需要优先检查 infile.eof() 才对。

if (infile.bad()) // 发生系统故障
    cout << "error: system failure" << endl;
else if (infile.eof())
    cout << "success: EOF" << endl; // 必须优先检查 eof 状态
else if (infile.fail())  // 读入数据失败
    cout << "error : read failure " << endl;
else
    // ...

参考链接:http://en.cppreference.com/w/cpp/io/basic_ios/fail

【热门文章】
【热门文章】