首页 文章

可以打印cout << '\n'乱码文字输出?

提问于
浏览
0

我有一个简单的程序来测试我正在编写的函数,它检测迷宫的文本文件是否有效 . 唯一允许的字符是 '0''1'' ' (空格)和 '\n' (换行符) . 但是,当我用示例文本文件执行代码时,我得到了一些奇怪的结果 . 如图所示,在打印导入的迷宫之前,下面图像的第三行应该是"Found an illegal character [char] at [location] in maze [number]",它会与文件匹配 .

enter image description here

main.cpp中:

#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

int main()
{
    string fileName = "Mazes/Invalid4.txt";
    string tempMaze;
    int createdMazes = 0;
    cout << "\nAttempting to open " << fileName;
    fstream thing;
    thing.open(fileName.c_str());
    if(thing.is_open())
    {
        cout << "\nHurray!";
        stringstream mazeFromFile;
        mazeFromFile << thing.rdbuf();
        tempMaze = mazeFromFile.str();
        for(int i = 0; i < tempMaze.size(); i++)
        {
            // test to make sure all characters are allowed
            if(tempMaze[i] != '1' && tempMaze[i] != '0' && tempMaze[i] != ' ' && tempMaze[i] != '\n') 
            {
                cout << "\nFound an illegal character \"" << tempMaze[i] << "\" at " << i << " in maze " << ++createdMazes << ": \n" << tempMaze;
                return 1;
            }
        }
        cout << " And with no illegal characters!\n" << tempMaze << "\nFinished printing maze\n";
        return 0;
    }

    else cout << "\nAw...\n";
    return 0;
}

是否有可能文本文件没有打破 '\n' 的行?这里发生了什么?

1 回答

  • 1

    您的文本文件很可能具有行结尾为CRLF( \r\n ) . 输出CR时,它会将光标移动到行的开头 . 从本质上讲,你发现了一个非法字符\“',然后将光标移动到行的开头并将其余部分写在它上面 . 你需要以不同的方式处理换行符来解决这个问题 .

相关问题