Code:
int a;
cin>>a;
cout<<a<<endl;
Then I use g++ test.cpp
, and run it. Then I input a letter 'b' to the variable a. The output is 0.
But, When I test the Other code:
cout<<int('b')<<endl; // output: 98
Why? What is the different?
int - numbers only without decimals. double - numbers with decimals. String - both numbers and letters.
Inputting Chars. We can use the std::cin function to read a char entered by the user via the keyboard. The std::cin will allow you to enter many characters.
Description. The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type.
One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.
std::cin
is an object, an instance of a std::istream
. std::istream
has overloaded the >>
to support a variety of types. One of those types is &int
. When there is a std::istream
on the left of >>
and an integer reference on the right, the method istream& operator>> (int& val)
is called. The conceptual implementation of that method is as follows.
When you provide 'b' as input to istream& operator>> (int& val)
, it immediately stores the "accumulated" 0 in your int
variable. Example:
#include <iostream>
int main (const int argc, const char * const argv[]) {
int b = 100;
std::cout << b << std::endl;
std::cin >> b;
std::cout << b << std::endl;
return 0;
}
Execution:
100
b
0
As for the cast, when you cast the value 'b'
to an integer, you already have a byte in memory with the value 98, which you then print as an integer. When you use >>
the resulting value in memory is 0, which you then print as an integer.
The input operation that you are trying to do is failing. Since a
is an int
cin
expects an int
. since it gets a char
it fails. You can test this by changing you code to:
int a;
cin>>a;
if(!cin)
cout << "input failed";
else
cout<<a<<endl;
Input:
a
Output:
input failed
See this live example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With