C++ cout 在擦除换行符后打印字符串不正确

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

本文关键字:打印 字符串 不正确 换行符 cout 擦除 C++      更新时间:2023-10-16

我有一个多行字符串:

123 456 7
8910

例如。我删除了函数int clean(string& text);中的所有换行符 '',并使用 cout 在主中打印字符串。结果是:

8910456 7

我知道我的函数工作"正确",因为str.substr(0, 5)的结果是:

123 4

此外,我正确地通过cout打印了另一个多行字符串,因此cout正常工作。还包括stringiostream图书馆。

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;
}
其他方法,擦除换行符,

例如将除换行符以外的每个字符添加到新字符串中,会产生相同的结果。我做错了什么?

你的行尾(我从你的结果推断(实际上是rn的,而不仅仅是n。 这是一个回车字节,后跟一个换行字节。

然后,您将第一行输出到cout,将字符串打印到控制台。 然后,您点击回车 ( r ( 字节,当输出到控制台时,将光标放回行的开头。 然后,第二行输出到控制台,但仍在同一行上,并打印在现有文本的顶部。