文件输入输出混乱

时间:2014-09-12 19:18:02

标签: c++

关于c ++在阅读eof方面的操作方式,我得到了相互矛盾的建议。 第一组人说当标记读取经过eof区域时,它到达eof并停止,而另一组人说它必须处于准确的位置,以便将其处理为到达eof。为了使这个更清楚,让我粘贴2块代码。

在这段代码中,我正在从文件numbers.txt中读取数字1。它们没有语法错误,我唯一没有粘贴的是打开文件的代码。

while (!sample.eof())
{
    char ch;
    sample.get(ch);
    sample.seekp(-1L, ios::cur);
    sample >> initialnumber;
    sample.seekp(2L, ios::cur);
    cout << "OK";
}

在这个程序中,我正在读取数字1向后移动一个空间,使其从开始处理它然后向前移动两个空格。这个输出只能写一次。

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

using namespace std;

string conversion(int);
int conversion2(string);

int main()
{

    string initialnumber;    
    fstream SAMPLE("numbers.txt", ios::in | ios::out);
    ofstream sample2("numbers2.txt");    
    if (sample && sample2)     
    {
        int number2;
        string roman;
        int number;
        char ch;
        while (!sample.eof()) {
            sample.get(ch);    
            if (ch != '1' && ch != '2' && ch != '3' && ch != '4' && ch != '5' && ch != '6'
            && ch != '7' && ch != '8' && ch != '9') {
                SAMPLE.seekg(-1L, ios::cur);
                sample >> roman;
                sample.seekg(2L, ios::cur);
                sample2 << roman << " " << conversion2(roman) << endl;
                int L = sample.tellp();
                cout << L;
            }
            else {
                sample.seekg(-1L, ios::cur);
                sample >> number2;
                sample2 << conversion(number2) << " " << number2 << endl;
                sample.seekg(2L, ios::cur);
            }
        }
    } 
    else  
    {
        cout << "fail";
    }    
    sample.close();    
    sample2.close();
}

这里重复无数次,不应该重复它,这意味着它永远不会到达eof。
请帮助我理解这两个程序的逻辑。

1 个答案:

答案 0 :(得分:0)

从C ++ 11开始

Before doing anything else, seekg clears eofbit.

http://en.cppreference.com/w/cpp/io/basic_istream/seekg

由于seekg始终是您在检查.eof()之前调用的最后一件事,因此永远不会检测到它。当读取操作到达文件末尾时,将设置eofbit。因此,阅读必须是你为它工作的最后一件事。

相关问题