Test cin input correct: unsigned int and negative number.

if i declare a unsigned int variable, and set a test loop to test if input correct. and when i type in a negative number, the loop still see it as input right. how can i make such a testing loop, which i declare a unsigned int, and when type in a negative number it tells wrong.


my invalide code following:
1
2
3
4
5
6
7
8
9
10
11
 int main()
{
	unsigned int i;
	while (!(cin >> i))
	{
		cout << "Wrong." << i << endl;
		cin.clear();
		while (cin.get() != '\n');
	}
	system("pause");
}
use stringstream.

First get the value using a string, check the first character in the string. If it is a '-', then do not accept, otherwise convert it to unsigned using this guide:

http://www.cplusplus.com/articles/D9j2Nwbp/
read section on string to number
Ya, it seems doable, thx :P

following is my code, help see where can be edit better :)

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
int main()
{
int x;
string sx = "x";
for(;;){
	if (!(cin >> x)){
		cin.clear();
		while (cin.get() != '\n');
		cout << "Wrong!" << endl;
		continue;
	}
	sx = to_string(long long(x));
	if (sx[0] == '-'){
		cout << "Wrong";
		continue;}
	if (cin.get() != '\n')
	{
		while (cin.get() != '\n');
		cout << "Wrong!" << endl;
		continue;
	}
	break;
}
cout << "!!";
system ("pause");
}
Topic archived. No new replies allowed.