while循环条件比较字符串的问题
question with while loop condition compare string
我正在尝试使以下代码正常工作。我希望它是这样的,如果输入的人名不是“x”,我希望它跳过循环并结束。如果没有,我希望它循环。我认为条件如下所示:
void printProfile()
{
//make a "cookie" or OBJECT
HealthProfile user;
//get name, age, weight, height info
string personName = " ";
int yrs;
double weight, feetHeight, inchesHeight;
//while the input isn't an x, keep going. if x is inputted, skip the while loop
while(personName != "x")
{
//prompt name
cout << "Enter name or X to quit: ";
getline(cin, personName);
//prompt age
cout << "Your age: ";
cin >> yrs;
//prompt weight
cout << "Your weight: ";
cin >> weight;
//prompt height feet
cout << "Your height - feet: ";
cin >> feetHeight;
//prompt height inches
cout << "Your height - inches: ";
cin >> inchesHeight;
user.setName(personName);
user.setAge(yrs);
user.setWeight(weight);
user.setHeight(feetHeight, inchesHeight);
cout << "Health Profile for " << user.getName() << endl;
cout << fixed << setprecision(1) << "BMI: " << user.getBMI() << endl;
cout << "BMI Category: " << user.getCategory() << endl;
cout << "Max heart rate: " << user.getMaxHR() << endl;
}
}
但它实际上在最后一次输入“x”时运行整个循环,然后结束程序。我该怎么做才能让输入 x 退出程序?
将循环条件更改为
while(true)
得到名字后,添加一个检查:
if((personName == "x")
break;
我正在尝试使以下代码正常工作。我希望它是这样的,如果输入的人名不是“x”,我希望它跳过循环并结束。如果没有,我希望它循环。我认为条件如下所示:
void printProfile()
{
//make a "cookie" or OBJECT
HealthProfile user;
//get name, age, weight, height info
string personName = " ";
int yrs;
double weight, feetHeight, inchesHeight;
//while the input isn't an x, keep going. if x is inputted, skip the while loop
while(personName != "x")
{
//prompt name
cout << "Enter name or X to quit: ";
getline(cin, personName);
//prompt age
cout << "Your age: ";
cin >> yrs;
//prompt weight
cout << "Your weight: ";
cin >> weight;
//prompt height feet
cout << "Your height - feet: ";
cin >> feetHeight;
//prompt height inches
cout << "Your height - inches: ";
cin >> inchesHeight;
user.setName(personName);
user.setAge(yrs);
user.setWeight(weight);
user.setHeight(feetHeight, inchesHeight);
cout << "Health Profile for " << user.getName() << endl;
cout << fixed << setprecision(1) << "BMI: " << user.getBMI() << endl;
cout << "BMI Category: " << user.getCategory() << endl;
cout << "Max heart rate: " << user.getMaxHR() << endl;
}
}
但它实际上在最后一次输入“x”时运行整个循环,然后结束程序。我该怎么做才能让输入 x 退出程序?
将循环条件更改为
while(true)
得到名字后,添加一个检查:
if((personName == "x")
break;