【问题标题】:Can printing cout << '\n' garble text output?可以打印 cout << '\n' 乱码文本输出吗?
【发布时间】:2015-05-31 06:48:42
【问题描述】:

我有一个简单的程序来测试我正在编写的函数,该函数检测迷宫的文本文件是否有效。唯一允许的字符是'0''1'' '(空格)和'\n'(换行符)。但是,当我使用示例文本文件执行代码时,会得到一些奇怪的结果。下图的第三行应在打印导入的迷宫之前显示“在迷宫 [编号] 中的 [位置] 处发现非法字符 [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' 换行?这是怎么回事?

【问题讨论】:

  • 嗨!您是否尝试在 HEX-editor 中检查文件内容?行也可以通过 Windows 中断序列“\r\n”来中断。

标签: c++ newline cout


【解决方案1】:

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

【讨论】:

  • 那么我可以检查'\r' 字符吗?我试过了,但它使每个迷宫的第一个字符的输出无效。我可以用不同的方式将文件读入字符串吗?
  • 您可以像检查\n 一样检查\r,这没有什么不同。如果您不需要它,请稍后丢弃它。
  • 好吧,我不知道为什么这之前不起作用。对乱码文本的很好解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-25
  • 2018-03-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-26
  • 2015-04-29
相关资源
最近更新 更多