我知道函数“ eof”(cpp)仅在尝试从文件中读取错误后才返回“ True”(而不是在到达文件末尾时才返回)

因此,如果我们要将所有文件从1移动到另一个文件,则必须执行

infile.get(c);
while ( !infile.eof() )
{
   outfile << c;
   infile.get(c);
}


并不是

while ( !infile.eof() )
{
   infile.get(c);
   outfile <<c;
}


因为如果我们采用第二种方式,最后一个字符将复制2次

但是在另一个程序上它不是那样工作的

我创建文件grades.txt并将其写为“ dani”

像这样的代码:

ifstream inGrade("grades.txt");
ofstream outRoster("roster.txt");

int tmpGrade;
inGrade >> tmpGrade;

while (!inGrade.eof() )
{

    outRoster << tmpGrade <<endl ;
    inGrade >> tmpGrade;
}


它创建“ roster.txt”,但不复制任何内容。

但是,如果我使用此代码:

ifstream inGrade("grades.txt");
ofstream outRoster("roster.txt");

int tmpGrade;


while (!inGrade.eof() )
{
    inGrade >> tmpGrade;
    outRoster << tmpGrade <<endl ;

}


它将创建roster.txt并将“ dani”复制到此处

为什么???为什么在这个示例中,当我们到达文件末尾而不是在错误地尝试从文件读取后,eof返回false。

最佳答案

我创建文件grades.txt并写在此“ dani”上


您的所有读取操作都将失败,因为无法将“ dani”提取为整数。这将设置流的故障位,但不消耗任何字符,因此不会设置eofbit。您的两个程序都应陷入无限循环。


  修复我不放丹妮,我放“ 100”


好的,那么您将不会陷入无限循环:)我编写了一个程序来演示该问题:

istringstream input("100");
int foo;

cout << "Reading int succesfully" << endl;
input >> foo;
cout << "!input:\t" << boolalpha << !input << endl;
cout << "input.eof():\t" << boolalpha << input.eof() << " << pay attention" << endl << endl;
cout << "Attempting to read eof" << endl;
input >> foo;
cout << "!input:\t" << boolalpha << !input << endl;
cout << "input.eof():\t" << boolalpha << input.eof() << endl << endl;

input.clear();
input.str("c");
char c;

cout << "Reading char succesfully" << endl;
input >> c;
cout << "!input:\t" << boolalpha << !input << endl;
cout << "input.eof():\t" << boolalpha << input.eof() << " << pay attention"  << endl << endl;
cout << "Attempting to read eof" << endl;
input >> c;
cout << "!input:\t" << boolalpha << !input << endl;
cout << "input.eof():\t" << boolalpha << input.eof() << endl << endl;


并输出:

Reading int succesfully
!input:      false
input.eof(): true << pay attention

Attempting to read eof
!input:      true
input.eof(): true

Reading char succesfully
!input:      false
input.eof(): false << pay attention

Attempting to read eof
!input:      true
input.eof(): true


因此,与读取格式化输入(例如数字)时相比,读取单个字符时eofbit的行为有所不同。

因此,如果要修改循环的版本,使其对数字和字符的行为相同,则需要使用bool转换而不是eof()来检查流的状态。另外,这将防止无效输入上的无限循环。您可以改用fail(),但是它不会检查badbit,因此当您遇到输入/输出错误时,它不会具有预期的行为。

infile.get(c);
while (infile) // or !infile.fail() if you have infallible hardware
{
   // use c
   infile.get(c);
}


应该工作以及

int tmpGrade;
inGrade >> tmpGrade;
while (inGrade)
{
    // use tmpGrade
    inGrade >> tmpGrade;
}


但是,您的方法将复制输入调用。您可以通过使输入处于循环状态来避免这种情况:

while (inGrade >> tmpGrade)
{
    // use tmpGrade
}

关于c++ - eof函数如何在cpp上工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28628027/

10-11 21:54