detect if user input is a number or no

Hey everyone, I was recently making a project that requires user input some numbers, however if you type in a char or some random words it goes all crazy. please help me and thx.
Could you post your code? This would help to give you a good answer(for your specific case) and not a generic one.
Do you absolutly nessarily need the code? I actually just want a general answer... thx for your time though.
The "general" answer is to get your input as a string and validate the contents of the string before using them.
give me an example please? thx
@ OP. I understand; thus, you are not required to post the code. Take a look at this link http://www.cplusplus.com/doc/tutorial/basic_io/ It may give you an idea.
give me an example please? thx

You don't want to supply code, but you wish code to be supplied to you?

There are plenty of examples out in the wild. Visit your favorite search engine.

(For instance a search on this site might lead you to this thread:
http://www.cplusplus.com/forum/beginner/108849/#msg592118 )
Last edited on
help plz... I just want a quick example... thx
There is an example at the URL linked immediately above your last post.
Here it is again.

http://www.cplusplus.com/forum/beginner/108849/#msg592118
closed account (LA48b7Xj)
cin will be flagged as fail if it didn't get the input it wanted. You have to clear the state to do more input operations. Here is a simple example for you...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>
using namespace std;

int main()
{
	while(true)
	{
		cout << "give me a number: ";

		int num;
		cin >> num;

		if(cin.eof() || cin.bad())
			break;

		if(cin.fail())
		{
			cin.clear();
			string s;
			getline(cin, s); 
			continue;
		}
		
		cout << "thank you for the number " << num << '\n';
	}
}
Last edited on
#WheatFieldOnFire

After you use cin on the next line do this:
1
2
3
4
5
6
7
8
9
while (cin.fail())
{
    std::cout << "Please enter a number: ";
    // Clears buffer in cin
    std::cin.clear();
    // Empty cin
    std::cin.ignore(1000000, '\n');
    std::cin >> yourVariable;
}

This will continue asking the user the re-enter a number if they give bad input.
thx guys! see i just wanted an example. Was that so hard?

thx again
thx guys! see i just wanted an example. Was that so hard?


You were linked an example (with more than one example in the linked-to thread.)

You could've searched for code samples.

I don't know why you felt it necessary to post this. Doing research is a part of programming. Waiting to be spoon-fed... not so much.
your example is too complicated, and it is too long. Why do you think i posted this question in beginner's post? krako's post is way easier than yours. though thx.
Last edited on
Topic archived. No new replies allowed.