2017-02-16 16 views
-9

Я пытаюсь использовать цикл while(1) в функции getCommand, но он работает бесконечно и не прерывается. Я включил функцию HELP, потому что она вызывается в функции getCommand. Вот код, о котором идет речь:используя while (1), но не могу разбить цикл в C++

void HELP(string inCommand) { 
    if (inCommand == "invLoad?") 
     cout << "This command allows the user to load in new inventory information into the report." << endl; 
    else if (inCommand == "invReport?") 
     cout << "This command allows the user to access an inventory report of a requested item." << endl; 
    else if (inCommand == "invPriceUpdate?") 
     cout << "This command allows the user to update the prices of a requested item." << endl; 
} 

//This is the function that acquires the SIMS command from the user 
string getCommand() 
{ 
    string commandInput = ""; 
    char quit = '.'; 
    cout << "Please enter the command for the Simple Inventory Management System:" << endl << 
    "invLoad, invReport, invPriceUpdate." << endl << endl; 
    cout << "To learn what each command does add a '?' at the end of the command input" << endl; 
    cin >> commandInput; 

    while (1) { 
     if (commandInput == "invLoad") { 
      return "invLoad"; 
     } 
     else if (commandInput == "invReport") { 
      return "invReport"; 
     } 
     else if (commandInput == "invPriceUpdate") { 
      return "invPriceUPdate"; 
     } 
     else if (commandInput == "invLoad?") 
      HELP(commandInput); 
     else if (commandInput == "invPriceUpdate?") 
      HELP(commandInput); 
     else if (commandInput == "invReport?") 
      HELP(commandInput); 
     else 
      cout << "Please enter an appropriate command!" << endl; 
     switch (quit) 
     { 
      case 'y': 
       return 0; 
       break; 

      case 'n': 
       cout << "Enter another command" << endl; 
     } 
    } 
} 

К сожалению, в то время как цикл выполняется бесконечно, и я не могу понять, как разорвать его.

+0

Он будет работать бесконечно, проверьте http://stackoverflow.com/questions/24278724/purpose-of-while1-statement-in-c –

+2

Вы можете использовать отладчик, чтобы узнать, что происходит. – pokey909

+0

Попробуйте ввести инструкцию cin в цикле, чтобы пользователь мог обновить значение commandInput в каждом цикле. – utopman

ответ

0

Контур переключения: его нельзя писать так.

вход «commandInput» является то, что должно быть зациклен на

правильное утверждение: переключатель (commandInput)

вы уже дали переменную бросить значение «» что приведет к тому, что компилятор не войдет в цикл, поскольку условие никогда не будет выполнено, поскольку вы всегда запрашиваете переменную commandInput как вход , поэтому при отладке кода вы фактически обнаружите, что цикл не введен, и именно поэтому вы цикл остается бесконечным