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

C++: Why cout is printing carriage return with the strings read from a file using ifstream?

我正在尝试读取文件 capitals,其内容如下:

Tokyo   
33200000
New York    
17800000
Sao Paulo   
17700000
Seoul
17500000
Mexico City
17400000

我用来打印文件内容的代码片段是:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    std::ifstream ifs("capitals");
    std::string s, s2;

    while (getline(ifs, s)) {
        getline(ifs, s2);
        cout << s  << ": "
             << s2 << endl;
    } 

    return 0;
}

但是,我得到的输出如下:

code_master5@Brahmaastra:~$ g++ test.cpp -std=c++17
code_master5@Brahmaastra:~$ ./a.out 
: 33200000
: 17800000  
: 17700000  
: 17500000
: 17400000y

预期输出的格式应为:

Tokyo: 33200000

原始输出的最后一行表明 cout 在打印城市名称后正在打印 carriage return。为什么会这样?

编辑 1: 根据 @Qubit 的建议,我使用 pop_back() 删除了最后一个字符。修改后的代码为:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    std::ifstream ifs("capitals");
    std::string s, s2;

    while (getline(ifs, s)) {
        s.pop_back();
        getline(ifs, s2);
        s2.pop_back();
        cout << s  << ": "
             << s2 << endl;
    } 

    return 0;
}

现在的输出是:

Tokyo   : 33200000
New York    : 17800000
Sao Paulo   : 17700000
Seoul: 17500000
Mexico City: 17400000

这些多余的空格是什么?

编辑 2 现在问题已经解决了。正如 @lubgr 所建议的那样,发生这种情况是因为文件以 windows 样式存储,每行末尾都有 \r。所以,我安装了 dos2unix 和 运行 以下命令:

code_master5@Brahmaastra:~$ dos2unix capitals 
dos2unix: converting file capitals to Unix format... 

然后,正如@codekaizer 进一步解释的那样,我保留了那些 pop_back() 调用以删除尾随的 '\t' 字符以获得预期的输出。

这是由您的 capitals 文件引起的,它的行以回车符 return 结尾(windows 样式),但是当您以非 [=18] 格式打印它时=] 终端,这些回车 return 没有正确处理。您有两个选择,运行

dos2unix captials

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

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

    /* ... */
}