Apfelvater
Apfelvater

Reputation: 1

C++ cout prints string incorrectly after erasing newline characters?

I had a multiline string:

123 456 7
8910

for example. I erased all newline characters '\n' in a function int clean(string& text); and printed the string in the main using cout. The result was:

8910456 7

I know my function works "right" because, the result of str.substr(0, 5) is:

123 4

Also, I had another multiline string printed out via cout correctly, so cout is working correctly. Also included string and iostream libraries.

int clean(string& text) {
    //...
    text.erase(std::remove(text.begin(), text.end(), '\n'), text.end());
    return 0;
}

int main() {
    string t1;
    string name1 = "../test.txt";
    try {
        t1 = readBlock(name1);
        cout << t1 << endl;
    } catch(exception &e) {
        cout << e.what();
    }
    cout << "Size: " << t1.size() << endl;
    clean(t1); //Here
    cout << t1 << "\n";
    return 0;
}

Other methods, erasing the newlines, like adding every character except newlines to a new string, resulted in the same. What am I doing wrong?

Upvotes: 0

Views: 148

Answers (1)

LordWilmore
LordWilmore

Reputation: 2912

Your line endings are (I infer from your result) actually \r\n rather than just \n. That is a Carriage Return byte, followed by a Line Feed byte.

You are then outputting the first line to cout which prints the string to the console. You're then hitting the carriage return (\r) byte which, when output to the console, puts the cursor back to the start of the line. The second line is then output to the console, but still on the same row, and it is printed over the top of the existing text.

Upvotes: 3

Related Questions