C++ 问题读取文本文件

标签 c++ text

我正在尝试学习 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/

相关文章:

c# - 反转数学函数

c# - 文本操作将单个文件中的类拆分为多个文件

android - 带有文本和图像的按钮 (Android)

javascript - 使用 jQuery get() 加载大型文本文件的最佳实践

c++ - DLL 内存损坏

c++对象创建相同类型的新实例

Javascript:如何从网页中检索文本

android - Android 5.1 上的 setTextColor

关于在 char 中放置一个小整数的 C++ 信息

c++ - cmake 无法在自定义位置或库存位置找到 boost