为什么c ++字符串流在读取文件时跳过第一个字节

问题描述 投票:0回答:1

我的代码是这样的:

   using namespace std;

    string pth("./xxx.pb");
    ifstream fin(pth, ios::in | ios::binary | ios::ate);
    int len = fin.tellg();
    fin.seekg(0);

    cout << "compare: \n";
    string s1(len, 0);
    fin.read(&s1[0], len);
    for (auto &el : s1)
        cout << (int)el << ", ";
    cout << endl;

    fin.clear();fin.seekg(0);
    stringstream ss;
    fin >> ss.rdbuf();
    for (auto &el : ss.str())
        cout << (int)el << ", ";
    cout << endl;

输出如下:

compare: 
10, 5, 104, 101, 108, 108, 111, 18, 2, 4, 6, 26, 7, 102, 108, 111, 97, 116, 51, 50, 32, 3, 
5, 104, 101, 108, 108, 111, 18, 2, 4, 6, 26, 7, 102, 108, 111, 97, 116, 51, 50, 32, 3, 

似乎字符串流从文件中读取时跳过了第一个字节。我的问题来自哪里?

c++ io fstream stringstream
1个回答
0
投票

使用fin >>输入字符串将跳过前导空格。参见cppreference

表现为FormattedInputFunction。在构造并检查了哨兵对象之后,它可能会跳过前导空格,...

因此文件开头的换行字符(ASCII为10)将被跳过。

© www.soinside.com 2019 - 2024. All rights reserved.