读取输入文件,但输出不符合我的预期

问题描述 投票:0回答:1

我的文件包含“abcdefg” 为什么当我使用这部分代码时,在控制台中,它会打印字母“g”。

`#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

int main () {
    char ch;
    fstream file;
    file.open("myfile.txt", ios::in);
   file.setf(ios::skipws);
    while (1)
    {
        file >> ch; 
        if (file.fail()) break;
        cout << ch; 
        cout << "\n";
    }
    file.close();
    return 0;
}
`

我希望输出除字母“g”之外的所有字符。

file readfile
1个回答
0
投票

对我来说,它给出了所有字母的输出。没关系,因为当它读取最后一个字母“g”时,流仍然没有处于失败状态,因此“g”被打印。当您尝试读取某些内容但无法读取(在“g”之后读取某些内容)时,流会进入失败状态。请参阅 fstream::fail() 文档设置失败位时的条件

© www.soinside.com 2019 - 2024. All rights reserved.