Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std cin work only when used with int variable?

Tags:

c++

c++11

I'm trying to use std::cin after a while.

Using uint8_t or unsigned char:

unsigned char data;
std::cin >> std::dec >> data;

Whatever std::dec is used or not, I get the first ASCII character I type. If I type 12, data is 0x31 not 12. Why can't it parse number until 255 to be stored in a char?

int data;
std::cin >> std::dec >> data;

gives correctly data=12/0xC not 0x31

  • Why?

Using char[N] with std::hex

char data[128];
std::cin >> std::hex >> data;

Also gets the ASCII characters instead of the hexadecimal.

  • Writting 0x010203040506... data is 0xFFFFFFFFF...

  • Isn't std::cin>>std::hex able to parse the string I type into hexadecimal automatically?

like image 526
Alexis Avatar asked Jul 31 '26 06:07

Alexis


2 Answers

In short:

  • cin >> charVar scans a single character from stdin
  • cin >> intVar scans characters from stdin until a non-numeric character is entered

Explaining your observation:

A char variable can store a single ASCII character.

When you type 12, only the character 1 is scanned.

The ASCII code of the character 1 is 0x31.

like image 153
goodvibration Avatar answered Aug 01 '26 18:08

goodvibration


std::dec and std::hex affect the format of integers.

But as far as the streaming operators are concerned, char and its variants (including uint8_t aren't integers, they're single characters. They will always read a single character, and never parse an integer.

That's just how these functions are defined. There is no way around it. If you want an integer with a limited range, first read into an int (or other integer type that is not a char variant), and then range-check afterwards. You can, if you want, cast it to a small type afterwards, but you probably shouldn't. char types are awkward to work with numerically.

Similarly, reading into an array of char reads a string. (Also, never do that without using setw() to limit the length to fit in the buffer you have. Better yet, use std::string instead.) That's just how it's defined.

like image 37
Sebastian Redl Avatar answered Aug 01 '26 19:08

Sebastian Redl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!