gpt4 book ai didi

C++ 验证循环问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:37:04 26 4
gpt4 key购买 nike

我是 c++ 的新手,非常接近解决方案,但我仍然需要一些帮助。我的循环第一次正常工作。在那之后,当我输入车号时,它似乎在某处抓取了一些输入,只是在第二遍执行了无效的颜色。显然,我遗漏了一些东西,但我不知所措。任何帮助将不胜感激。

这只是我程序的一小段,但问题就在这里:

while (count < 3)
{
cout << endl << "Enter car color: blue, red or green in lower case. ";
getline(cin, carColor[count]);

if (!(carColor[count] == "blue" || carColor[count] == "red" || carColor[count] == "green"))
{
cout << "That is an invalid color"
<< "The program will exit";
cin.clear();
cin.ignore();
return 0;
}


cout << endl << "Enter car number between 1 and 99: ";
cin >> carNumber[count]; // Enter car number
if (carNumber[count] >99 || carNumber[count] < 1)
{
cout << "That is not a correct number"
<< " The program will exit";
return 0;
}

cout << "car no is:" << carNumber[count] << "color: " << carColor[count];


++count;
// int lapCount{ 1 };

cout << endl;

}

最佳答案

cin >> carNumber[count]; 中按 enter 后的 '\n' 字符在执行第二遍 后可能仍然存在getline(cin, carColor[count]); 你得到一个空字符串。一种解决方案是这样做:

char c;
cin >> carNumber[count];
cin >> c;

但更好的解决方案是改变:

getline(cin, carColor[count]);

到:

cin >> carColor[count];

关于C++ 验证循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36672112/

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