C++ cin fails when reading more than 127 ASCII values

て烟熏妆下的殇ゞ 提交于 2019-12-04 06:48:34

std::cin reads text streams, not arbitrary binary data.

As to why the 26th character is interesting, you are probably using a CP/M derivative (such as MS-DOS or MS-Windows). In those operating systems, Control-Z is used as an EOF character in text files.


EDIT: On Linux, using g++ 4.4.3, the following program behaves precisely as expected, printing the numbers 0 thru 255, inclusive:
#include <iostream>
#include <iomanip>

int main () {
  int ch;
  while( (ch=std::cin.get()) != std::istream::traits_type::eof() )
    std::cout << ch << " ";
  std::cout << "\n";
}

I presume you are on windows. On the windows platform character 26 is ctrl-z which is used in a console to represent end of file, so the iostreams is thinking your file ends at that character.

It onlt does this in text mode which cin is using, if you open a steam in binary mode it won't do this.

There are two problems here. The first is that in Windows the default mode for cin is text and not binary, resulting in certain characters being interpreted instead of being input into the program. In particular the 26th character, Ctrl-Z, is being interpreted as end-of-file due to backwards compatibility taken to an extreme.

The other problem is due to the way cin >> works - it skips whitespace. This includes space obviously, but also tab, newline, etc. To read every character from cin you need to use cin.get() or cin.read().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!