Why is character 'a' not converted to 97 automatically?

c++, character, inputstream, integer

Solution

`a`, as a string, is not convertible to an `int` by the rules `std::cin` follows. Consider this: `a` is not a valid integer in base 10. `std::cin` will fail to convert the string `"a"` to an `int`.

The reason it prints `-858993460` is because the `int` is not initialized, so it could print anything, or nothing, or do whatever it desires (look up undefined behaviour).

Try something like this instead:

char input2_chr;
std::cin >> input2_chr;
int input2 = input2_chr;

Problem

``` char input1; std::cout << "input1 : "; std::cin >> input1; int input2; std::cout << "input2 : "; std::cin >> input2; std::cout << input1 << std::endl; std::cout << input2 << std::endl; return 0; ``` I wrote 'a' at input1 and 'a' at input2. ``` Ouput is like this. input1 : a input2 : a a -858993460 ``` I'm curious...'a' charter is 97 in dec. why does it print -858993460? 'a' is not converted to 97 automatically? why?

Original source

Related problems