Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using cin.get to get an integer

Tags:

c++

casting

I want to get a string of numbers one by one, so I'm using a while loop with cin.get() as the function that gets my digits one by one.

But cin.get() gets the digits as chars and even though I'm trying to use casting I can't get my variables to contain the numrical value and not the ascii value of the numbers I get as an input.

like image 382
Quaker Avatar asked Nov 16 '12 17:11

Quaker


People also ask

How do I get an int in C++?

To declare an int variable in C++ you need to first write the data type of the variable – int in this case. This will let the compiler know what kind of values the variable can store and therefore what actions it can take. Next, you need give the variable a name. Lastly, don't forget the semicolon to end the statement!

What is the use of CIN get ()?

get() is used for accessing character array. It includes white space characters. Generally, cin with an extraction operator (>>) terminates when whitespace is found.

How do you check if a value is an integer in C++?

Apply isdigit() function that checks whether a given input is numeric character or not. This function takes single argument as an integer and also returns the value of type int.

How do I convert a string to an int in C++?

Using the stoi() function The stoi() function converts a string data to an integer type by passing the string as a parameter to return an integer value. The stoi() function contains an str argument. The str string is passed inside the stoi() function to convert string data into an integer value.


1 Answers

cin.get can’t parse numbers. You could do it manually – but why bother re-implementing this function, since it already exists?*

int number;
std::cin >> number;

In general, the stream operators (<< and >>) take care of formatted output and input, istream::get on the other hand extracts raw characters only.


* Of course, if you have to re-implement this functionality, there’s nothing for it.

To get the numeric value from a digit character, you can exploit that the character codes of the decimal digits 0–9 are consecutive. So the following function can covert them:

int parse_digit(char digit) {
    return digit - '0';
}
like image 69
Konrad Rudolph Avatar answered Oct 28 '22 07:10

Konrad Rudolph