繁体   English   中英

C ++ cout删除换行符后无法正确打印字符串?

[英]C++ cout prints string incorrectly after erasing newline characters?

我有一个多行字符串:

123 456 7
8910

例如。 我在int clean(string& text);函数中删除了所有换行符'\\ n' 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;
}

擦除换行符的其他方法(例如将除换行符之外的每个字符都添加到新字符串中)也是如此。 我究竟做错了什么?

您的行尾实际上是(我从您的结果推断) \\r\\n而不只是\\n 这是回车字节,后跟换行字节。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM