imulsion
imulsion

Reputation: 9040

Is there a way to test if an input is a number in C++?

Question's all in the title. I'm making a calculator and I obviously need input. I use the cin>> function but I was wondering if there is a way to test the input to find out if it's a number. If I enter anything that isn't a number the program crashes. Is there a built in function/operator? Please help!

Upvotes: 1

Views: 156

Answers (2)

Bo Persson
Bo Persson

Reputation: 92261

The input operator will only read to an integer if the input is a number. Otherwise it will leave the characters in the input buffer.

Try something like this

int i;
if (cin >> i)
{
    // input was a number
}
else
{
    // input failed
}

Upvotes: 3

Valerij
Valerij

Reputation: 27748

atoi and sscanf are your friends, or just compare if the entered charcode is within the "0"-"9" range

Upvotes: 0

Related Questions