我正在尝试使用C++,并在阅读文本文件时收到以下错误.知道为什么吗?
输入:
This is a test.
A test, with tabs and too many spaces.
If this is a good one,
then all will be well.
Run Code Online (Sandbox Code Playgroud)
输出:
then all will be well. too many spaces.
Run Code Online (Sandbox Code Playgroud)
码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
您使用一个使用UNIX行结尾(\n)的实现,并解释\r为将光标返回到行的开头.该文件包含旧的Mac OS行结尾(\r),这意味着getline()读取直到文件末尾并将所有内容\r放入字符串中,导致您稍后将其打印到控制台.