0

I am new to C++ and something wrong is happening,

Basically, I have declared a variable called number which is of type int.

If I input a string such as a or x... then number becomes 0. I don't want number to become 0 and instead want it to be error handled.

How do I prevent this is C++? This is my source code...

#include <iostream>
using namespace std;

int number;

int main() {
    cout << "Please input a number: ";
    cin >> number;
    cout << number << endl;
    return 0;
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Sam Kooloo
  • 21
  • 1

2 Answers2

2

You need to check what happened in cin:

if (cin >> number) {
    cout << number << endl;
}
else {
    cout << "error: I wanted a number." << endl;
}
Barry
  • 286,269
  • 29
  • 621
  • 977
  • Thanks @Barry :), what about `double` inputs? For example, if I input `9.5` then number = `9`, but I also want an error message to pop up – Sam Kooloo Nov 20 '14 at 20:53
  • if you need full input validation then proper way to input a string and then use something like regular expression. – Slava Aug 26 '16 at 16:35
0

For this you can store the value in a temporary string and then do some conversions to int and double:

#include <iostream>
#include <string> 
#include <stdlib.h> //needed for strtod
using namespace std;
int main() {
    string str;
    cin >> str; //Store input in string
    char* ptr;  //This will be set to the next character in str after numerical value
    double number = strtod(str.c_str(), &ptr); //Call the c function to convert the string to a double
    if (*ptr != '\0') { //If the next character after number isn't equal to the end of the string it is not a valid number
        //is not a valid number
        cout << "It is not a valid number" << endl;
    } else {
        int integer = atoi(str.c_str());
        if (number == (double)integer) { //if the conversion to double is the same as the conversion to int, there is not decimal part
            cout << number << endl;
        } else {
            //Is a floating point
            cout << "It is a double or floating point value" << endl;
        }
    }
    return 0;
}

Please note that global variables are bad, write them inside a scope (a function or a class, for example)