my program will read in a string from user input, how do i check if it is a number?
my program will read in a string from user input, how do i check if it is a number?
I think you can answer your own question by asking yourself: What is a number?
i tried using isdigit, but it is not working. Or maybe anyone can tell me how to use isdigit() to check if the string is a number?
Here's a pretty good reference for you to answer questions like this on your own.
http://www.cppreference.com/
Now, they still use the older header files like ctype.h instead of the newer, prefered headers like cctype, but that's a minor consideration.
For now, you need to include either the ctype.h or the cctype header file in your program in order to use isdigit(). Then one syntax you could use couuld be something like this:
Code:char ch = '1'; if(isdigit(ch)) cout << "ch is a digit";
You're only born perfect.
> i tried using isdigit, but it is not working
It's usually a good idea to post your attempt rather than just complaining "it didn't work".
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
If you are reading from cin, the simplest method is to use cin's built-in number checking. The easiest way to do that is to check the return value of cin:Sometimes people would prefer a loop that prompts the user to try again:Code:if (cin >> myint) // myint is a numberFinally, sometimes people want to also make sure that a number followed by text doesn't count either (e.g. 42g is not a number):Code:while (!(cin >> myint)) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); // re-prompt. }At this point it works pretty well, although there are still other features that can be added. At some point it is overkill, thuogh, so the above should work fine for checking if the input is a number.Code:while (!(cin >> myint) || cin.get() != '\n') { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); // re-prompt. }
If you have a string, use a stringstream instead of cin, and of course get rid of the loop.