我正在尝试学习 C++,但在读取文本文件时出现以下错误。知道为什么吗?
输入:
This is a test.
A test, with tabs and too many spaces.
If this is a good one,
then all will be well.
输出:
then all will be well. too many spaces.
代码:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
ifstream infile ("A5.txt");
if (infile.is_open()) {
while (!infile.eof()) {
getline(infile,line);
cout << line << endl;
}
infile.close();
}
return 0;
}
最佳答案
您使用一个使用 UNIX 行结尾 (\n
) 的实现,并解释 \r
以将光标返回到行的开头。该文件包含旧的 Mac OS 行结尾 (\r
),这意味着 getline()
读取文件末尾并将所有 \r
到字符串中,使您稍后将它们打印到控制台。
关于C++ 问题读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14297935/