ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c – ifstream不读取EOF字符

2019-09-25 16:05:34  阅读:183  来源: 互联网

标签:ifstream eof c


我正在创建一个程序(在C中),它接受一个ASCII文件并从每一行读取一些值,直到它到达文件的末尾.我使用ifstream来读取文件,当我使用ifstream.eof()方法时,我从未遇到过停止问题.但是,这一次,即使它在我的测试用例中找到了eof字符,当我分析其他文件时,它仍然是无限循环,因为它永远不会找到eof字符.这是编码问题,还是我的文件问题?

string line = "";
unsigned long pos = 0;
ifstream curfile(input.c_str());
getline(curfile, line);
int linenumber = 0;
cout<<"About to try to read the file"<<endl;
if (!curfile.good())
    cout<<"Bad file read"<<endl;
while (!curfile.eof())
{

    cout<<"Getting line "<<linenumber<<endl;
    linenumber++;
    pos = line.find_first_of(' ');
    line = line.substr(pos+1, line.size()-1);
    pos = line.find_first_of(' ');
    current.push_back(atof(line.substr(0, pos).c_str()));
    for (int i = 0; i<4; i++)
    {
        pos = line.find_first_of(' ');
        line = line.substr(pos+1, line.size()-1);
    }
    pos = line.find_first_of(' ');
    dx.push_back(atof(line.substr(0, pos).c_str()));
    pos = line.find_first_of(' ');
    line = line.substr(pos+1, line.size()-1);
    pos = line.find_first_of(' ');
    dy.push_back(atof(line.substr(0, pos).c_str()));
    getline(curfile, line);
}

编辑:当我第一次运行循环时,currentfile.good()返回false …我在做什么导致它返回?

解决方法:

首先,你不应该那样检查. eof()在读取失败之前不会返回true.但你可以做得更好(也更容易)!

检查流状态,隐式转换为void *,可以在bool上下文中使用.由于流上的大多数读操作都返回对流的引用,因此您可以编写一些非常简洁的代码,如下所示:

std::string line;
while(std::getline(currentfile, line)) {
    // process line
}

基本上它正在做的是说“虽然我可以成功地从当前文件中提取一行,但执行以下操作”,这无论如何都是你真正要说的;-);

就像我说的,这适用于大多数流操作,所以你可以做这样的事情:

int x;
std::string y;
if(std::cin >> x >> y) {
    // successfully read an integer and a string from cin!
}

编辑:我将重写您的代码的方式是这样的:

string line;
unsigned long pos = 0;
int linenumber = 0;

ifstream curfile(input.c_str());

std::cout << "About to try to read the file" << std::endl;
while (std::getline(curfile, line)) {

    std::cout << "Getting line " << linenumber << std::endl;
    linenumber++;

    // do the rest of the work with line
}

标签:ifstream,eof,c
来源: https://codeday.me/bug/20190925/1816188.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有