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!

7
  • possible duplicate of How to convert a number to string and vice versa in C++ Commented Jul 29, 2012 at 9:22
  • 1
    @KillianDS it is not about "converting a number to string", but "checking if an input is a number" Commented Jul 29, 2012 at 9: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. Commented Jul 29, 2012 at 9:26
  • @KillianDS, sure, you can use a regex. Commented Jul 29, 2012 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. Commented Jul 29, 2012 at 11:46

2 Answers 2

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 } 
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

you should put some examples in your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.