When I declare int weight
and then input a double value 165.1
a 2nd cin >> height;
doesn't work and there is no any error message. Can you tell me why?
VS2010 Console Application used.
#include <iostream>
using namespace std;
const double lbs_to_kg = 2.2046, inches_to_meter = 39.370;
int main()
{
int weight, height;
double kilograms, meters;
cout << "\nEnter weight in pounds: ";
cin >> weight;
kilograms = weight / lbs_to_kg;
cout << "\nEnter height in inches: ";
cin >> height;
meters = height / inches_to_meter;
cout << "\nYour BMI is approximately "
<< "\nbody fat ratio is "
<< kilograms / (meters * meters)
<< ". Under 25 is good."
<< endl;
}
output:
Enter weight in pounds: 165.1
Enter height in inches:
Your BMI is approximately
bod开发者_JAVA百科y fat ratio is 1.57219e-013. Under 25 is good.
If you try to have cin
extract data into a variable that can't hold it, the data is left in the input stream and cin
is flagged as having failed. You need to check if it's failed with !cin
, and use cin.clear()
to clear the fail flag so you can read again (future extract operations will automatically fail until the flag is cleared). You can either extract the data into a different variable that's capable of holding it, or use cin.ignore()
to discard it
精彩评论