intcreator
intcreator

Reputation: 4414

Can printing cout << '\n' garble text output?

I have a simple program to test a function I'm writing that detects if a text file for a maze is valid. The only allowed characters are '0', '1', ' ' (space) and '\n' (newline). However, when I execute the code with a sample text file, I get some strange results. The third line of the following image should read "Found an illegal character [char] at [location] in maze [number]" before printing the imported maze as shown, which it does and it matches the file.

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;
}

Is it possible that the text files aren't breaking lines with '\n'? What's going on here?

Upvotes: 0

Views: 151

Answers (1)

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31143

Your text file most likely has line endings as CRLF (\r\n). When you output CR, it will move the cursor to the beginning of the line. In essence, you're first writing 'Found an illegal character \"', then moving the cursor to the beginning of the line and writing the rest on top of it. You need to handle the line breaks differently to fix this.

Upvotes: 1

Related Questions