简体   繁体   中英

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!

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
}

atoisscanf是你的朋友,或者只是比较输入的charcode是否在“0” - “9”范围内

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM