我正在尝试读取文件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 正在打印回车打印城市名称后。为什么会发生这种情况?
EDIT 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
这些额外的空间是什么?
EDIT 2现在问题已经解决了。正如建议的@lubgr,发生这种情况是因为文件以 Windows 样式存储,每行末尾带有 \r。所以,我安装了dos2unix并运行以下命令:
code_master5@Brahmaastra:~$ dos2unix capitals
dos2unix: converting file capitals to Unix format...
然后,正如 @codekaizer 进一步解释的那样,我保留了这些 pop_back() 调用以删除尾随的 '\t' 字符以获得预期的输出。