Providing error message for Number Guessing project

I'm trying to provide an error message if the user input a character/string, but I'm not sure how to do so.

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include "pch.h"
#include <iostream>


using namespace std;

int main()
{
	//declaring variables
	int Num1,Input,Tries;

	//initialise variables
	Num1 = 678;
	Tries = 0;
	
	do
	{
		cout << "Please enter a number: ";
		cin >> Input;
		Tries++;
		if (isalpha(Input))
		{
			cout << "Please enter a valid number";
		}
		else if (Input > Num1)
		{
			cout << "Try a smaller number." << endl;
		}
		else if (Input < Num1)
		{
			cout << "Try a larger number." << endl;
		}
		else
		{
			cout << "Yes you are correct. You have guessed " << Tries << " times" << endl;
		}
	
	} while (Input != Num1 );

	return 0;
}
Like so
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
if ( cin >> Input ) {
    if (Input > Num1)
    {
        cout << "Try a smaller number." << endl;
    }
    else if (Input < Num1)
    {
        cout << "Try a larger number." << endl;
    }
    else
    {
        cout << "Yes you are correct. You have guessed " << Tries << " times" << endl;
    }
} else {
    // If you land here, then the input could not be parsed as an
    // integer, or the input stream reached EOF
}

Check how it failed
http://www.cplusplus.com/reference/ios/ios_base/iostate/

Reset the error
http://www.cplusplus.com/reference/ios/ios/clear/

Clean up the input stream of invalid characters
http://www.cplusplus.com/reference/istream/istream/ignore/


Topic archived. No new replies allowed.