我的循环工作正常,直到我输入最后一个值作为性别的输入,当输入“true”时,循环忽略其余循环的 cin,只打印 cout 中的文本,直到循环结束,任何想法如何让循环在每个循环上都要求输入,或者我在哪里犯了错误? ps:这是一项功课,所以我无法更改给出的结构。感谢您的任何建议。代码片段:
int main()
{
struct Patient
{
double height;
double weight;
int age;
bool isMale;
};
Patient ListOfPatients[4];
int iii = 0;
while (iii < 4)
{
cout << "enter the height (eg. 1.80 metres) of patient number " << iii + 1 << " :" << endl;
cin >> ListOfPatients[iii].height;
cout << "enter the weight (eg. 80kg) of patient number " << iii + 1 << " :" << endl;
cin >> ListOfPatients[iii].weight;
cout << "enter the age of patient number " << iii + 1 << " :" << endl;
cin >> ListOfPatients[iii].age;
cout << "is the patient a male? (true = male or false = female) " << endl;
cin >> ListOfPatients[iii].isMale;
iii++;
}
return 0;
}
最佳答案
问题是当您阅读 isMale
时. bool
确实是一个数字,0
对于 false
, 1
对于 true
.您无法将字符串读入其中。
发生的情况是,您最终在流中得到了一堆字符,这些字符无法被任何 >>
读取。操作,所以它们都连续失败。尝试传入 1
或 0
在命令行上,一切正常。
如果您希望用户能够传入一个字符串,然后将其视为 bool
,您可以使用专门为此提供的实用程序,或手动执行此操作以帮助您理解。
要使用标准实用程序,它称为 std::boolalpha
并出现在 <iomanip>
header :
std::cin >> std::boolalpha >> ListOfPatients[i].isMale;
要手动执行此操作,请将其读入 std::string
反对并自己做一些比较,就像这样:
std::string tmpIsMale;
std::cin >> tmpIsMale;
ListOfPatients[i].isMale = (tmpIsMale == "true");
正是出于这个原因,在尝试读取流后检查流的状态也是一个好主意。您可以将流直接放入 if
为此:
std::cin >> someVariable;
if (!cin) { // cin is not in a good state
std::cerr << "Failed to read someVariable, please try again with a proper value!\n";
return 1;
}
您可能希望避免的一些旁白和不良做法:
-
using namespace std;
被广泛认为是不好的做法。 -
std::endl
有点争议,但您使用它的方式表明您不理解它。 - 性别不是 bool 值选项。我知道这不是一个严格的技术问题,如果结构是由你的老师提供的,你就有点卡住了,但是拜托,现在是 2019 年了!学习编写好的程序并不仅仅意味着语言的技术细节,还包括学习如何编写对用户有益的程序,所以尽早养成良好的习惯是个好主意。
关于c++ - while 循环不提示用户输入 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55124887/