我有一个简单的程序来测试我正在编写的功能,该功能可以检测迷宫的文本文件是否有效。唯一允许的字符是'0''1'' '(空格)和'\n'(换行符)。但是,当我使用示例文本文件执行代码时,会得到一些奇怪的结果。下图的第三行应显示为“在迷宫[number]的[位置]的[位置]发现非法字符[char]”,然后打印导入的迷宫,如图所示,它与文件匹配。



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'换行?这里发生了什么?

最佳答案

您的文本文件很可能以CRLF(\r\n)结尾。当您输出CR时,它将光标移动到行首。本质上,您首先要写“发现一个非法字符\“”,然后将光标移动到该行的开头,然后将其余内容写在该行的开头。您需要以不同的方式处理换行符以解决此问题。

关于c++ - 可以输出cout <<'\n'乱码输出吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30554664/

10-11 22:57
查看更多