【问题标题】:Weird symbol when reading file in C++用 C++ 读取文件时出现奇怪的符号
【发布时间】:2016-11-20 19:34:48
【问题描述】:

我正在使用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;
     };

这是正在输出的内容:

【问题讨论】:

  • while( text &lt;&lt; fstream ) cout &lt;&lt; text;不是更干净吗?
  • 您输入文件的实际内容是什么?
  • 这段代码对我来说很好用。问题可能出在“In.txt”
  • 这是记事本中的一个文件。它只包含“abc def ghi”
  • @IanBaughman 你能上传吗?出于某种原因,微软的家伙喜欢插入你不想要的字符(例如,BOM)。

标签: c++ fstream ifstream


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 2014-07-18
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多