C++ primer 习题8.9的问题
阿神
阿神 2017-04-17 11:23:14
[C++讨论组]

一切都进行的很顺利,就是在输出的时候,总是读取数据错误,即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;
}
阿神
阿神

闭关修行中......

全部回复(1)
巴扎黑

在文件遇到 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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号