how to reject bad input?
Oct 10, 2013 at 5:59pm Oct 10, 2013 at 5:59pm UTC
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 Oct 10, 2013 at 6:02pm UTC
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 Oct 10, 2013 at 6:29pm UTC
Last edited on Oct 10, 2013 at 6:32pm Oct 10, 2013 at 6:32pm UTC
Oct 10, 2013 at 7:44pm Oct 10, 2013 at 7:44pm UTC
Last edited on Oct 10, 2013 at 8:21pm Oct 10, 2013 at 8:21pm UTC
Oct 12, 2013 at 1:26pm Oct 12, 2013 at 1:26pm UTC
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.