another quick question

hi,

easy one, i hope, in a simple program, where the user is requested to input a number (stored as an int), if the user accidentally inputs a letter the console crashes instantly, how would I prevent the prog from crashing if a letter was accidentally entered intead of an int?
I'm using visual C++ express 2008.

Thanks.
You will need to check the stream for errors after your cin >> num;, otherwise
you don't know if num was filled out successfully.
thanks for the response, how does one check the stream for errors?
could you give me an example?
Last edited on
thanks spaggy, but how do I implement this? forgive me I am very fresh to C++, the bool good(); looks like it will do the job alright, how would I implement this in the code?

e.g.
int number;
cout << "please enter a number" << endl;
cin >> number;


how do I implement bool good() here as to flag if a letter is incorrectly entered as an int?

thanks.
cin is an istream so good is a member of cin.

so right after cin >> number, check the value of cin.good().

Sort of like
1
2
3
4
5
6
7
8
if(cin.good())
{
//do stuff as normal
}
else
{
//print an error or something
}
Ok tried this in a quick test (code below) and it still fails, compiles fine but when I enter a letter the console screen crashes (loops continuously)? Have I implemented this correctly? whould this detect the error in a letter being entered?

1
2
3
4
5
6
7
8
9
10
11
12
13
	//test
	cout << endl << "please enter a number " << endl;
	int number;
	cin >> number;

	if (cin.good())
	{
		cout << endl << number << endl;
	}
	else
		cout << "you need to enter a number" << endl;
	
}
Hi all,

quick update, the above code actually works ok if I run one time, however if I try to loop and request a number a second time ot continually loops (doesnt seem to execute the cin again.

I have written some simple code below (probably over complex), the intent here is to request an input number, check that a number is input (if a letter instead of a number is input it should request a number again). Now when this code is executed it works of for a number but when I input a letter it just loops without again prompting for a number? Can anyone explain why this is?
Thanks.

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
#include <iostream>
using namespace std;
bool test();
int main()
{
	test();
	while (test()== false)
	{
		test();
	}

	return 0;
}

bool test()
{
	unsigned short int number;
	cout << "please enter a number " << endl;
		cin >> number;

		if (cin.good())
		{
			cout << number << endl;
			return true;	
		}
		else
			cout << "you need to enter a number" << endl;	
			cin.clear();
			return false;
}
hi,

sussed it!

needed a cin.sync() post the cin.clear()

Topic archived. No new replies allowed.