且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C++:为什么 cout 使用 ifstream 从文件中读取的字符串打印回车?

更新时间:2023-11-14 12:14:46

这是由你的 capitals 文件引起的,它有一个以回车符结尾的行(windows 样式),但是当你打印它时在非 Windows 终端中,这些回车没有得到正确处理.你有两个选择,要么运行

This is caused by your capitals file, it has line ending with a carriage return (windows style), but when you print it in a non-Windows terminal, these carriage returns aren't properly handled. You have two options, either run

dos2unix captials

这将从行尾中删除所有回车字符,或者按照@Qubit 在注释中的建议,您可以删除 while 循环中的最后一个字符:

which will remove all carriage return characters from the line endings, or as suggested by @Qubit in the comments, you get rid of the last character inside the while loop:

while (getline(ifs, s)) {
    getline(ifs, s2);
    s.pop_back();
    s2.pop_back();

    /* ... */
}