我正在写0到255个ascii字符,并试图逐个字符读取它,但不能在第25个字符后读取

I am writing 0 to 255 ascii character and trying to read it character by characte but cant read after 25th character

本文关键字:字符 读取 但不能 25个 255个 ascii      更新时间:2023-10-16

代码片段如下:

int main()
{
  char ch=26;
  ofstream fout;
  fout.open("key.txt");
  if (fout.is_open())
  {
    for(int i=0; i<256; i++)
    {
      ch=i;
      fout << ch;
      cout<<ch;
    }
    fout.close();
  }
  else
    cout << "Unable to open file";
  string line;
  ifstream fout1 ("key.txt");
  if (fout1.is_open())
  {
    while (fout1)
    {
      fout1.get(ch);
      cout <<" "<< (int)ch<<" "<<ch<<"t ";
    }
    fout1.close();
  }
  else
    cout << "Unable to open file";
  return 0;
}

我发现,当读取第26个字符它停止程序。如果转义,则读取所有其他字符。注意我使用的是Code Blocks IDE

无法读取第26个字符的原因是它的值为26。这在文本文件中被解释为文件结束标记。你必须以二进制格式打开你的文件,然后它将工作。

在显示的代码中,我建议您先关闭输出文件,然后再打开它进行读取。这将确保缓冲区中的任何字符都被刷新到磁盘。此外,在阅读之后,如果程序没有在那里结束,您可能也希望刷新cout

还要注意一些字符是不可打印的,或者在打印时做一些奇怪的事情(比如跳到行首,或者删除已经打印的内容)。