Так что я просто не могу понять, что не так с моим кодом. Когда я обрабатываю покупку, после того, как я ввожу количество йогурта, и мне сказали, чтобы он наслаждался им, я сразу же получил сообщение об ошибке, которое я сделал, если люди не вводят P или S, а затем сразу возвращается к нормальной жизни это когда вы впервые входите в программу, может кто-нибудь сказать мне, почему это? Спасибо!Я не могу понять, почему эта петля неисправна
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string userCommand;
int creditCount = 0;
int userInput;
while (creditCount >= 0)
{
cout << "--------Menu--------\n" << "P (Process Purchase)\n" << "S (Shutdown System)\n"
<< "--------Menu--------\n" << "Your Choice: ";
getline(cin, userCommand);
if (userCommand[0] == 'P' || userCommand[0] == 'p')
{
if (creditCount >= 10)
{
cout << "You qualify for a free yogurt, would you like to use ten of your credits (Yes or No)?";
getline(cin, userCommand);
if (userCommand[0] == 'Y' || userCommand[0] == 'y')
{
creditCount = creditCount - 10;
cout << "You just used 10 credits and now have " << creditCount << " left.\n"
<< "Enjoy your free yogurt!";
}
else if (userCommand[0] == 'N' || userCommand[0] == 'n')
{
cout << "How many yogurts would you like to buy? ";
cin >> userInput;
if (userInput > 0)
{
creditCount = creditCount + userInput;
cout << "You just earned " << userInput << " stamps. You now have " << creditCount
<< " credits! Enjoy your yogurt!";
}
else
{
cout << "Invalid input, please try processing your purchase again and enter a positive "
<< "integer.";
}
}
else
{
cout << "*Error, please try processing your purchase again and enter either Yes or No*\n\n";
}
}
else if (creditCount < 10)
{
cout << "How many yogurts would you like to buy? ";
cin >> userInput;
if (userInput > 0)
{
creditCount = creditCount + userInput;
cout << "You just earned " << userInput << " stamps. You now have " << creditCount
<< " credits! Enjoy your yogurt!\n\n";
}
else
{
cout << "Invalid input, please try processing your purchase again and enter a positive "
<< "integer.";
}
}
}
else if (userCommand[0] == 'S' || userCommand[0] == 's')
{
cout << "*Shutting down system*\n";
return 0;
}
else
{
cout << "*Error, please enter either P (for Process Purchase) or S (for Shutdown System)*\n\n";
}
}
}
Возможный дубликат (http://stackoverflow.com/questions/21567291/why- do-stdgetline-skip-input-after-a-format-extract) – LogicStuff
Проще говоря, после того, как вы сделаете 'cin >> userInput;', 'std :: getline' будет читать то, что осталось на той же строке. Вызов 'userCommand [0]' на пустом 'userCommand' также является UB. – LogicStuff
Возможный дубликат [cin и getline passipping input] (http://stackoverflow.com/questions/10553597/cin-and-getline-skipping-input) – Barmar