Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input a letter to 'int'

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?

like image 586
green2rabbit Avatar asked Jun 18 '15 02:06

green2rabbit


People also ask

Can you use int for letters?

int - numbers only without decimals. double - numbers with decimals. String - both numbers and letters.

How do you input a letter in C++?

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.

Which function converts value into integer?

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.

How do I convert a string to a number in C++?

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.


2 Answers

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.

  1. Store 0 in an accumulator
  2. Read a character of the input
  3. If the character is 0-9, add its decimal value to the accumulator
  4. If not, return the value of the accumulator
  5. Return to step 2

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.

like image 92
OregonTrail Avatar answered Oct 03 '22 01:10

OregonTrail


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

like image 30
NathanOliver Avatar answered Oct 03 '22 03:10

NathanOliver