【问题标题】:How to read substitution char with ifstream in C++ ? (SUB in ASCII)如何在 C++ 中用 ifstream 读取替换字符? (ASCII 中的 SUB)
【发布时间】:2014-03-21 01:20:37
【问题描述】:

我很难找出为什么我不能使用 fstream get 函数读取所有字符。 我的代码如下:

ifstream input_stream(input_filename.c_str(), ios::in);
string input;

if(input_stream)
{
    char character;
    while(input_stream.get(character))
    {
        input += character;
    }
    input_stream.close();
}
else
    cerr << "Error" << endl;

通过一些测试,我发现当 character = 26(ASCII 中的 SUB)时出现问题,因为 input_stream.get(26) 返回 false 并且我退出了 while 循环。 我想在我的字符串中输入文件中的所有字符,包括 SUB。 我一开始尝试使用 getline 函数,但遇到了类似的问题。 你能帮我吗?

【问题讨论】:

  • 在哪个操作系统上?
  • 必须是 Windows - 亲爱的老 control-z 又来了。

标签: c++ ascii ifstream getline substitution


【解决方案1】:

您需要读取二进制流,而不是文本流(因为 SUB'0x1a'(即 26)是 ASCII 或 UTF8 中的控制字符,而不是可打印的)使用 @ 987654321@开放时间:

 ifstream input_stream(input_filename.c_str(), ios::in | ios::binary);

也许你会编码

 do {
   int c= input_stream.get();
   if (c==std::char_traits::eof()) break;
   input += (char)c;
 } while (!input_stream.fail());

您是否考虑过使用std::getline 读取整行,假设输入文件仍以('\n' 终止)行组织?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    相关资源
    最近更新 更多