Checking to see if something is a number with if statements

Okay I need to check to see if what the user inputs is a number and not another character if it is a character print error. I was thinking I could do if x is not greater than or not less and equal to zero (which means it has to be a number), print error message. How would I possibly do this with if statements?
A more C-styled approach would work...


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <stdio.h> //Needed for scanf

using namespace std;

int main()
{
    int num;

    cout << "Please input a number...\n> ";

    if (scanf("%d", &num) == 1) //asks for input and if it comes back with a number ("%d") then it outputs the input, else, an error
        cout << "You entered " << num << "\n";
    else
        cout << "Error. That's not a number...\n";

    return 0;
}

Hm I have never used scanf before I don't think that's what my teacher is looking for, is there any other simpler alternatives I could try, like for loops or while loops?
Give this a Google: type checking C++

It brings up lots of info and threads that should help.
Last edited on
istream::peek() or read as number and fail.
Topic archived. No new replies allowed.