help with getData function
Feb 10, 2008 at 3:48am UTC
i'm trying to right the definition of a function that prints a prompt and returns the value that the user input. if the value entered is negative it will print a predefined error message, dump all characters left on the line following the input, and ask for another value until a valid one is entered.
this is what i have so far
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
double getInput(string prompt)
{
double value;
cout << "Enter the " << prompt << endl;
cin >> value;
if (value<0) {
do {
cout << ERROR_MESSAGE << endl;
cout << "Enter the " << prompt << endl;
cin >> value;
}
while (value<0);
}
return value;
}
double altitude, fuelSupply, tractorBeamStrength;
altitude=getInput("current altitude of the ship (km): " );
fuelSupply=getInput("current fuel supply of the ship (kg): " );
tractorBeamStrength=getInput("strength of the enemy tractor beam (km/min/min): " );
i don't think it seems to be working -- any suggestions?
Feb 11, 2008 at 4:36am UTC
You need to add another argument ERROR_MESSAGE if it was not already defined. Also, you can clear cin by adding a couple of ignore commands.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
const char ERROR_MESSAGE[] = "Enter a value greater than 0." ;
double getInput(string prompt)
{
double value;
cout << "Enter the " << prompt << endl;
cin >> value;
cin.ignore (BUFSIZ, '\n' );
if (value<0) {
do {
cout << ERROR_MESSAGE << endl;
cout << "Enter the " << prompt << endl;
cin >> value;
cin.ignore (BUFSIZ, '\n' );
}
while (value<0);
}
return value;
}
double altitude, fuelSupply, tractorBeamStrength;
altitude=getInput("current altitude of the ship (km): " );
fuelSupply=getInput("current fuel supply of the ship (kg): " );
tractorBeamStrength=getInput("strength of the enemy tractor beam (km/min/min): " );
Topic archived. No new replies allowed.