gpt4 book ai didi

c++ - Loop 在获取输入之前完成一个循环,如何解决?

转载 作者:行者123 更新时间:2023-11-28 08:14:32 25 4
gpt4 key购买 nike

while (1)
{
cout << "Enter the Citizen ID number of the worker or Enter 0 to exit:" << endl;
getline (cin, j);
for (i=0; i<5; i++)
{
if (workers[i]->IDno == j)
{
wFind = 1;
cout << "Choose your option:" << endl;
cout << "1- Display all details of the worker" << endl;
cout << "2- Display number of the days worker delayed" << endl;
cout << "3- Display number of the days worker missed" << endl;
cin >> k;
switch (k)
{
case 1:
workers[i]->AWorker();
break;
case 2:
cout << workers[i]->TotalDaysDelayed() << endl;
break;
case 3:
cout << workers[i]->TotalDaysMissed() << endl;
break;
default:
break;
}
}
else
wFind = 0;
}

if (wFind == 0)
cout << "ERROR: No worker has the ID number that you typed!" << endl;
}

注意:wFind初始化为2

当我执行这段代码时,我总是得到这样的输出:

Enter the Citizen ID number of the worker or Enter 0 to exit:
ERROR: No worker has the ID number that you typed!
Enter the Citizen ID number of the worker or Enter 0 to exit:

有趣的是,我的代码可以在获取字符串 j 的输入之前完成循环中的一个循环。这怎么可能?我该如何解决?

最佳答案

cin >> k; 不会吃掉换行符。您需要在它之后调用 std::getline 来使用换行符。

如果您在循环的第一次迭代中遇到问题,我会假设您在上面的代码也不会吃掉换行符。

关于c++ - Loop 在获取输入之前完成一个循环,如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8086622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com