我对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;
}
答案 0 :(得分:4)
在'\n'
中按Enter后,cin >> carNumber[count];
字符可能仍然保持不变,执行getline(cin, carColor[count]);
的第二次传递后,您将获得一个空字符串。一种解决方案是:
char c;
cin >> carNumber[count];
cin >> c;
但更好的解决方案就是改变:
getline(cin, carColor[count]);
为:
cin >> carColor[count];