help with if statement/loop

I am doing this RNG code for a project, I have it almost all the way finished, but am having an issue with one last thing.

I need to know how to put the following into code form


You are asked to guess a number
If you guess a letter (Non number)
You got it wrong, terminate program

My guess would be something like

1
2
3
if (guess != "A number")
cout << "You have not guessed a number, terminating program." << endl;
return 0;


what would i replace "A number" with, and would I need to initialize any other variables/libraries for such?
closed account (48T7M4Gy)
It all depends whether you're asking for a single digit or larger.

If it's a single digit then make guess a char and check whether guess isdigit()

See http://www.cplusplus.com/reference/cctype/isalpha/?kw=isalpha is gives you lot's of food to solve for more complicated scenarios.

<string> might have a similar functionality, I'm not sure what it is. In fact you could use strings and just run through each character that makes up the string to make sure each is a digit. :)
Last edited on
Just check if std::cin failed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
	int input;

	std::cin >> input;
	if(std::cin.fail())
	{
		std::cout << "Invalid input. Exiting.\n";

		return 0;
	}

	std::cout << "Valid input. Still exiting.\n";

	return 0;
}
Last edited on
closed account (48T7M4Gy)
On first glance it appears to work. But! input 2a and we get 'valid input' message.

http://www.cplusplus.com/reference/ios/ios/fail/
You are correct.

Anyway, here's a link to something that does in fact work properly:
http://www.cplusplus.com/forum/beginner/13044/#msg62827
Topic archived. No new replies allowed.