I wrote the following code to check whether the input(answer3) is a number or string, if it is not a number it should return \"Enter Numbers Only\" but it returns the same e
This is a somewhat old question, but I figured I'd add my own solution that I'm using in my code.
Another way to check if a string is a number is the std::stod
function, which has been mentioned, but I use it a bit differently. In my use case, I use a try-catch block to check if the input is a string or number, like so with your code:
...
try {
double n = stod(answer3);
//This will only be reached if the number was converted properly.
cout << "Correct" << endl;
} catch (invalid_argument &ex) {
cout << "Enter Numbers Only" << endl;
}
...
The primary problem with this solution is that strings that begin with numbers (but aren't all numbers) will be converted to numbers. This can be easily fixed by using std::to_string
on the returned number and comparing it to the original string.