how to reject bad input?

Oct 10, 2013 at 5:59pm
this is part of a function that I am working on I am getting it to work but now I need to make it display "Error" if user enters a non numeric value for both Miles and Gallons but I have no idea where to start please help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  void FindMilesPerGallon(void)
{
	
	float Miles, Gallons, MPG;

	MPG = 0;

  cout << "Enter miles driven ==> ";
  cin >> Miles;
  cout << "Enter gallons consummed ==> ";
  if(cin >> Gallons)
  { MPG = Miles/ Gallons;
  cout << "Total miles per gallon :" << MPG;
}
	  
	 
Oct 10, 2013 at 6:02pm
check cin for fail status after getting input:
1
2
3
4
5
6
7
8
9
if (!(cin >> Miles)) {
    std::cout <<  "Error";
    return 1;
}
//or
cin >> Miles;
if (cin.fail()) {//Or !cin, however they not actually the same thing
    //...
}
Oct 10, 2013 at 6:29pm
To expand on MiiNiPaa's response, look at this page:
http://www.parashift.com/c++-faq/istream-and-ignore.html

It'll show you how to detect bad input, tell the user it was bad, clear cin's 'fail' state, and prompt the user again.
Last edited on Oct 10, 2013 at 6:32pm
Oct 10, 2013 at 7:44pm
See:

Trying to limit input to int type
http://www.cplusplus.com/forum/beginner/108849/

in particular cire's post:
http://www.cplusplus.com/forum/beginner/108849/#msg592118

And:

how to deny non-numeric input?
http://www.cplusplus.com/forum/beginner/109874/

Andy

PS Regarding:

however they not actually the same thing

Actually, using

if (!cin)

is the same as

if (cin.fail())

At least if basic_ios::operator!() follows the C++ standard and returns fail();

(same kind of deal for basic_ios::operator void*() -- it returns a null pointer if fail(), otherwise "some" non-null pointer.)
Last edited on Oct 10, 2013 at 8:21pm
Oct 12, 2013 at 1:26pm
Now I have an infinite loop every time I enter a number where do I change the loop control variable to break out of the loop?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void FindMilesPerGallon(void)
{

	float Miles, Gallons, MPG;

	MPG = 0;

	cout << "Enter miles driven ==> ";
	cin >> Miles;

	cout << "Enter gallons consummed ==> ";
	if (cin >> Gallons)
	{
		MPG = Miles / Gallons;
		cout << "Total miles per gallon :" << MPG;
	}
	if (!(cin >> Miles) || !(cin >> Gallons)) {
		cout << "Error";
		Miles = 0;
		Gallons = 0;
		MPG = 0;
	}

}
Topic archived. No new replies allowed.