2017-02-16 19 views
-9

我試圖在getCommand函數中使用while(1)循環,但它運行無限且不會中斷。我已經包含了HELP函數,因爲它在getCommand函數中被調用。這是有問題的代碼:雖然(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-while-statement-in-c –

+2

你可以使用調試器來找出發生了什麼事情。 – pokey909

+0

嘗試在循環中放置cin指令,讓用戶有機會更新每個循環的commandInput值。 – utopman

回答

0

開關循環:不應該這樣寫。

輸入「commandInput」是什麼東西應該

被環正確的說法是:開關(commandInput)

你已經給變量退出值「」這將導致編譯器不進入循環,因爲您永遠不會滿足條件,因爲您總是要求commandInput變量作爲輸入 ,因此當您調試代碼時,您會發現循環未輸入,這就是爲什麼您循環仍然無限