Mac/Linux getline 无法读取文件内容(读取内容无法显示)

如下面代码

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    string file_name = "1.txt";
    std::ifstream file(file_name);

    if (file.is_open()) {
        std::string line;
        while (std::getline(file, line)) {
            char c = line.back();
            cout << static_cast<int>(c) << endl; // 13
            cout << c << endl;    // 无法显示
            cout << line << endl; // 无法显示
            break;
        }
        file.close();
    } else {
        std::cout << "无法打开文件" << std::endl;
    }
    return 0;
}

我发现我读取的文件每行的 line 是有大小的,说明读取到了每行的内容,但是通过 cout 打印就是空的

经过我的研究,我发现读取每行的内容里末尾有个 \r,在 ASCII 码里是 13,有这个 \r 就会导致读取的每行的内容无法正常打印,而在 windows 上是能正常识别 \r 的

所以解决办法就是删除每行的 \r 就能正常显示了

Mac\Linux 的这个 getline 只能按照 \n 截取,像是遇到 \r\n 这种格式,就留下一个 \r,导致字符串无法正常显示

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值