How to use cin to enter a single-byte integer? If you enter in char / unsigned char, then a character is entered, but not a number. Is it possible to somehow configure it so that cin enters a number into char, not a character? I know that you can enter in int and then convert to char, but it is just input to single-byte that interests you without creating temporary ints.

  • one
    Good question, unexpected. - VladD

2 answers 2

@ Waylander123 , obviously not at all what you wanted, but something similar (of course, in C (and maybe you knew C in C), but g ++ perceives it), but cin >> could not be overcome.

(The comment did not fit, I had to answer).

 avp@avp-ubu1:~/hashcode$ cat tttx.cpp #include <iostream> #include <stdlib.h> #include <stdio.h> using namespace std; int main(int ac, char *av[]) { char x; scanf("%hhd", &x); cout << "C++: x=" << (x & 0xff) << '\n'; printf ("C: x=%d\n", x & 0xff); } avp@avp-ubu1:~/hashcode$ g++ tttx.cpp avp@avp-ubu1:~/hashcode$ ./a.out 12 C++: x=12 C: x=12 avp@avp-ubu1:~/hashcode$ ./a.out 234 C++: x=234 C: x=234 avp@avp-ubu1:~/hashcode$ 

Note the format of "% hhd" in scanf() . The hh modifier points to 1 byte.

    No, through std::istream ( std::cin ) you cannot enter char as a number.

    std::istream uses std::num_get::get , which does not have overloads for char .

    However, std::num_get::get uses std::strtoll to enter std::strtoll numbers,
    therefore, reading the int from std::cin and converting it to char is the right solution.