用C ++读取文件时的奇怪符号

时间:2016-11-20 19:34:48

标签: c++ fstream ifstream

我正在使用fstream来访问文件并提取其内容。当我输出其数据时,我继续得到一个奇怪的符号。这是我正在使用的过程。我之前已经成功使用它,但现在我似乎遇到了问题。这是代码。

    #include<iostream>
    #include<fstream>

    using namespace std;

    int main() {
        char text;
        int waitForIt;
        fstream Txt1("In.txt", ios::in);


        cout << "\n\tcontents of In.txt:" << endl << endl;
        cout << "\t\t";
        Txt1.get(text);
        do {
            cout << text;
            Txt1.get(text);
        } while (!Txt1.eof());
        Txt1.close();
        cin >> waitForIt;
     };

这是输出的内容:

Symbol being output as char text

1 个答案:

答案 0 :(得分:1)

我打赌你的文件无法打开。您编写循环的方式是,即使读取失败,也可以使用get函数打印您认为已读过的字符。

你应该这样做:

fstream Txt1("In.txt", ios::in);
if ( Txt1.is_open() )
{
    cout << "\n\tcontents of In.txt:" << endl << endl;
    cout << "\t\t";
    while (!Txt1.eof())
    {
        Txt1.get(text);
        cout << text;
    }
    Txt1.close();
}
else
{
    cout << "Unable to open file" << endl;
}