c++ - printing cout << '\n' 乱码输出可以吗?

标签 c++ newline cout

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

enter image description here

主要.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++ - printing cout << '\n' 乱码输出可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30554664/

相关文章:

reflection - Rebol为什么不换新线?类似地对待换行关键字和换行符吗?

newline - 如何在 Bitbucket markdown 中新写一行?

javascript - 如何在 JavaScript 中通过换行符从字符串创建数组?

c++ - std::cout 如何知道在哪里打印?

c++ - 输出 float 为三位数,或更多以避免指数

c++ - 使用 qcompleter 自动完成单词中间的片段

c++ - 自动检测基类的类型参数

XCode 4 在几十行后停止打印到调试区

c++ - 左子右兄弟表达式树

C++ 到 Ruby : find substring in a string