Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Basic C++

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
When I enter a letter this goes into an infinite loop asking to input correct data but not waiting for input.


float getGallons()
{
/* Description: Gets # of gallons for one purchase.
Preconditions: None
PostConditions: Returns gallons for 1 purchase
PseudoCode:
----------------------------------------
While Gallons is not correct
Prompt and input gallons
If cin stream is bad or gallons <= 0
Display error and get gallons again
If gallons is > 50
Make sure gallons is correct
return gallons
---------------------------------------- */

float gallons=0;
char yn='n';

while ( yn == 'n' ){
yn = 'y';
cout << &quot;How many gallons did you get at your last purchse?: &quot;;
cin >> gallons;

while ( !cin || gallons <=0 ){
cout << &quot;Please enter a gallon amount above 0: &quot;;
cin >> gallons;
}

if ( gallons > 50 ){
cout << gallons << &quot; is a large amount of gas for one car.&quot;
<< endl << &quot;Are you sure this is the right amount? (y/n): &quot;;
cin >> yn;

while ( yn != 'n' && yn != 'y' ){
cout << &quot;Please type y (yes) or n (no): &quot;;
cin >> yn;
}
}
}

return gallons;
}
 
This has happened to me before as well. You have 2 options,
1. Make sure you only enter numbers
2. Read the input into a string and convert the value using atof(input);

Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top