【问题标题】:C++ Strange File OutputC++ 奇怪的文件输出
【发布时间】:2011-05-30 23:51:44
【问题描述】:

我正在尝试从一个简单的文本文件中读取。每当我运行程序时,它都会打印出文件, 但不是在打印出一堆乱码之前。有什么建议吗?

乱码:

Φ#·  ├ï Uï∞ Φ╖   ≈╪←└≈╪YH]├ 5tδ╝
 abc    

缓冲区.cc

//-----------------------------------------------------
//  TextInputBuffer  - Constructor for TextInputBuffer.
//-----------------------------------------------------
TextInputBuffer::TextInputBuffer(char *InputFileName)
{
    //--Open file. Abort if failed.
    InputFile.open(InputFileName, std::ios::in);
    if (!InputFile.good()) exit(1);
}

//-----------------------------------------------------
//  GetNextLine      - Get next line from input file.
//
//  Return: The first character of the next line.
//-----------------------------------------------------
char TextInputBuffer::GetNextLine()
{
    //--Get next line from input file.
if (InputFile.eof()) *ptrChar = eofChar;
else
{
    InputFile.getline(Text, MaxInputBufferSize);
    ptrChar = Text;
}

return *ptrChar;
}

//-----------------------------------------------------
//  GetNextChar      - Get next character from the text
//                     buffer.
//
//  Return: The next character in the text buffer.
//-----------------------------------------------------
char TextInputBuffer::GetNextChar()
{
    char ch;

    if      (*ptrChar == eofChar) ch = eofChar;
    else if (*ptrChar == eolChar) ch = GetNextLine();
    else
    {
        ++ptrChar;
        ch = *ptrChar;
    }

    return ch;
}

列表.cc

TextInputBuffer InputBuffer(argv[1]);
char ch;

do {
    ch = InputBuffer.GetNextChar();

    if (ch == eolChar)
        std::cout << std::endl;

    std::cout << ch;
} while (ch != eofChar);

【问题讨论】:

  • 您可以尝试使用非常低级的文本编辑器或对文件的前几个长字进行十六进制转储,以尝试匹配“一堆乱码”。
  • 不,它不够低级,因为它很容易被不同的字符编码混淆(缺少 BOM 尤其成问题)。使用十六进制编辑器。
  • 我刚做了,只有 616263(又名 abc)。我也认为 MRAB 是对的。

标签: c++


【解决方案1】:

我会从一些惯用的代码开始读取和显示您的数据。如果这不起作用,那么您的输入文件很可能不包含您的预期。如果它确实有效,那么您看到的问题就在您现有代码的某个地方。

#include <iostream>
#include <string>

int main(int argc, char**argv) { 
    std::ifstream in(argv[1]);
    std::string line;

    while (std::getline(in, line))
        std::cout << line << "\n";
    return 0;
}

现在,您似乎正在使用 iostreams,但使用它们的方式非常奇怪,以至于很难猜测您是否做错了什么,如果是,究竟是什么。在任何情况下,几乎所有代码似乎都在尝试复制 iostreams(和流缓冲区)已经做的事情。如果您真的只想一次读取一个字符,请执行此操作。尝试编写自己的缓冲通常是浪费时间;如果/当它真的不是时,通常最好将缓冲代码写在实际的流缓冲区中,而不是作为 iostream 的包装器。

【讨论】:

    【解决方案2】:

    我认为它在打开文件后不会读取第一行,因此它会从未初始化的行存储中获取垃圾字符,直到一个恰好是换行符,此时它实际上读取了第一行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-03
      • 2011-06-14
      • 2023-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多