[英]while loop not prompting for user input (c++)
我的循环工作正常,直到我输入最后一个值作为性别的输入,当输入“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>
标头中:
std::cin >> std::boolalpha >> ListOfPatients[i].isMale;
要手动执行此操作,请将其读入std::string
对象并std::string
进行一些比较,如下所示:
std::string tmpIsMale;
std::cin >> tmpIsMale;
ListOfPatients[i].isMale = (tmpIsMale == "true");
正是出于这个原因,在尝试读取流之后检查流的状态也是一个好主意。 您可以将流直接放入if
for this:
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
有点争议,但你使用它的方式表明你不理解它。 您不能将字符串true
分配给布尔字段。 请检查更正的示例。
int main()
{
struct Patient
{
double height;
double weight;
int age;
bool isMale;
};
Patient ListOfPatients[4];
int iii = 0;
while (iii < 4)
{
string sIsMale = "";
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 >> sIsMale;
ListOfPatients[iii].isMale = sIsMale == "true";
iii++;
}
return 0;
}
您可以使用流操纵器boolalpha
来自己进行任何比较:
cin >> std::boolalpha >> cListOfPatients[iii].isMale >> std::noboolalpha;
这里的问题是isMale
是一个boolean
,字符串"true"
与boolean
! 它之所以没有崩溃而只是运行程序的其余部分,是因为你的cin
仍在从输入流中读取旧字符。 一个简单的解决方案是将true或false转换为布尔值,然后使用这些来设置isMale
。 这可以通过以下方式完成:
String toBeConverted;
cin >> toBeConverted;
ListOfPatients[iii].isMale = toBeConverted == "true";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.