【问题标题】:Why does C++ stringstream skip the first byte when I read a file为什么当我读取文件时 C++ stringstream 会跳过第一个字节
【发布时间】:2020-03-10 02:17:26
【问题描述】:

我的代码是这样的:

   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, 

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

【问题讨论】:

  • @paddy 我不使用&gt;&gt;,如何将其添加到我的代码中?
  • 我不明白。你fin &gt;&gt; ss.rdbuf()的人,对吧?所以它会变成fin &gt;&gt; std::noskipws &gt;&gt; ss.rdbuf()
  • 对不起,我的错,我已经按照你的建议解决了这个问题。非常感谢。

标签: c++ io fstream stringstream


【解决方案1】:

使用fin &gt;&gt; 输入字符串将跳过前导空格。见cppreference

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

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

【讨论】:

    猜你喜欢
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多