C ++奇怪文件输出

问题描述

| 我正在尝试从一个简单的文本文件中读取。每当我运行程序时,它都会打印出文件, 但在打印出一堆乱码之前不会。有什么建议么? 断章取义:
Φ#·  ├ï Uï∞ Φ╖   ≈╪←└≈╪YH]├ 5tδ╝
 abc    
缓冲液
//-----------------------------------------------------
//  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;
}
List.cc
TextInputBuffer InputBuffer(argv[1]);
char ch;

do {
    ch = InputBuffer.GetNextChar();

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

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

解决方法

        我不认为打开文件后会在读取第一行,因此它会从未初始化的行存储中获取垃圾字符,直到碰巧是换行符为止,此时它实际上会读取第一行。     ,        我将从一些惯用的代码开始,以读取和显示您的数据。如果这不起作用,那么您的输入文件很可能没有您期望的内容。如果它确实有效,那么您遇到的问题就是您现有代码中的某个地方。
#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;
}
现在,您似乎正在使用iostream,但是奇怪地使用了它们,因此很难猜测您是否做错了什么,如果真的做错了什么。无论如何,实际上您的所有代码似乎都在尝试复制iostream(和流缓冲区)已经做过的事情。如果您真的只想一次读取一个字符,请执行此操作。尝试编写自己的缓冲通常是浪费时间。如果/实际上不是,通常最好在实际的流缓冲区中编写缓冲代码,而不是将其包装在iostream上。