2016-01-27 2 views
0

Так что я просто не могу понять, что не так с моим кодом. Когда я обрабатываю покупку, после того, как я ввожу количество йогурта, и мне сказали, чтобы он наслаждался им, я сразу же получил сообщение об ошибке, которое я сделал, если люди не вводят 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"; 
     } 

    } 
} 
+5

Возможный дубликат (http://stackoverflow.com/questions/21567291/why- do-stdgetline-skip-input-after-a-format-extract) – LogicStuff

+1

Проще говоря, после того, как вы сделаете 'cin >> userInput;', 'std :: getline' будет читать то, что осталось на той же строке. Вызов 'userCommand [0]' на пустом 'userCommand' также является UB. – LogicStuff

+1

Возможный дубликат [cin и getline passipping input] (http://stackoverflow.com/questions/10553597/cin-and-getline-skipping-input) – Barmar

ответ

1

Проблема в том, что getline возвращает пустую строку.

Итак, после вашего первого раза через цикл, он возвращается к началу, чтобы прочитать другую строку. Возвращает пустую строку, которая вызывает ошибку.

Вы можете исправить это, проверив пустую строку после getline.

2

@ acid1789 правильно указал, что ошибка связана с пустой линией после getline. Из вашего кода, что я могу сделать из это вы используете бесконечный цикл здесь

while(creditCount >= 0){...} 

так creditCount никогда не будет меньше 0, вместо этого вы можете использовать

while (true){...} 

его просто лучше программирование практика.

И исправить вашу программу, вы можете просто использовать

cin >> userCommand; 

вместо

getline(cin, userCommand); 

Надеется, что это помогает.

Edit: - [? Почему станд :: GetLine() пропустить ввод после отформатированный извлечения] К сожалению привычки Python ..

Смежные вопросы