I'm not sure of the logic in your head, either. Being a psychic sure would help in times like these, haha. I think Duthomhas might be one.
So, to start... what makes you think that a negative number is not a number? You hurt -1's feelings, you know.
But on a more serious note, by starting your data type as an
int, you are already starting off on the wrong leg, because what else can an int be interpreted as, other than an integer number? An int means integer, i.e the countable set {..., -2, -1, 0, 1, 2, 3, ...}. It couldn't hold a value like "a" or "apple" to begin with.
Basically, what you want to do is initially request the input in the form of a string, because a string could be "apple", "-3.14", "1", or "0xDEADBEEF", etc. Then, you need to logically parse the string to see if it can be interpreted as a number. C++ provides a relatively easy way to do this for most use cases, with std::stringstreams.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
// Example program
#include <iostream>
#include <string>
#include <sstream>
int main()
{
using namespace std;
cout << "Enter a number, or whatever: ";
string str;
cin >> str;
istringstream ss(str);
int num;
if (ss >> num) // attempt conversion from istringstream to int
{
cout << "It's a number! num = " << num << endl;
}
else
{
cout << "Not a number I can recognize." << endl;
}
}
|
__________________________________
Edit: joe's method will work fine, too. My only minor criticism is that the cin.fail check is separated from the call to cin itself, leading to external dependencies in the interface.
The following could work as well, just a simplified version of joe's
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
// Example program
#include <iostream>
#include <string>
int main()
{
using namespace std;
cout << "Enter a number: ";
int n;
if (cin >> n)
{
cout << "You entered " << n << endl;
}
else
{
cout << "Hey! You didn't enter a number..." << endl;
}
}
|