C++ - 从ifstream读取字符

Tug*_*.44 -3 c++ fstream file visual-studio-2013

我正在尝试从文件中读取字符,但陷入无限循环,这是代码:

#include "stdafx.h"
#include <iostream>
#include <fstream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    ifstream ifs("ifile.txt", ios_base::in);
    int b;
    while ((b = ifs.get()) != EOF)
    {
        cout << b << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,我在正在创建 .exe 文件的项目 Debug 文件夹中创建了一个名为 ifile.txt 的文件(我使用的是 Microsoft Visual Studio 2013)

当我运行它时,它陷入无限循环。不知道为什么会发生这种情况,但我认为它可能与我创建 ifile.txt 的地方有关?

Gal*_*lik 6

请永远不要循环eof()它几乎总是错误的。

尝试这个:

ifstream ifs("ifile.txt", ios_base::in);

char b;
int letters[26] = {};
int numbers[10] = {};

while(ifs.get(b))) // much better !!
{
    cout << b << endl;
}
ifs.close();
Run Code Online (Sandbox Code Playgroud)

解释中:

使用时存在几个问题eof()EOF仅在您尝试读取角色后才会触发。我知道这并不完全是您使用它的方式。另一个问题是EOF在流上发生错误后不会检查(也许是无限循环?)这就是为什么最好检查读取是否成功而不是是否到达文件末尾。