1

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!

imulsion
  • 8,820
  • 20
  • 54
  • 84
  • possible duplicate of [How to convert a number to string and vice versa in C++](http://stackoverflow.com/questions/5290089/how-to-convert-a-number-to-string-and-vice-versa-in-c) – KillianDS Jul 29 '12 at 09:22
  • 1
    @KillianDS it is not about "converting a number to string", but "checking if an input is a number" – Rafi Kamal Jul 29 '12 at 09:25
  • 1
    @rafl: you cannot check if it is a number without at least trying to convert. And most conversion functions offer a "fail" mechanism that you can use here. No need to reinvent the wheel at all. – KillianDS Jul 29 '12 at 09:26
  • @KillianDS, sure, you can use a regex. – edA-qa mort-ora-y Jul 29 '12 at 11:12
  • @edA-qamort-ora-y and what does that regex actually do? It tries to interpret the string as a number, sounds much like conversion to me. It's not the method that you use for conversion that matters. – KillianDS Jul 29 '12 at 11:46
  • It does not convert. It matches a string against a pattern. That is quite different from conversion. – edA-qa mort-ora-y Jul 29 '12 at 12:02
  • @edA-qamort-ora-y yes, matching or interpretation is the first step in conversion, it is also often the step that contains the failure-checks. – KillianDS Jul 29 '12 at 12:30

2 Answers2

3

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
}
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
0

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

Valerij
  • 27,090
  • 1
  • 26
  • 42