使用while(1)但不能在c ++中打破循环

时间:2017-02-16 21:36:41

标签: c++ while-loop infinite-loop

我试图在while(1)函数中使用getCommand循环,但它无限运行并且不会中断。我已经包含了HELP函数,因为它是在getCommand函数中调用的。以下是有问题的代码:

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;
        }
    }
}

不幸的是,while循环无限运行,我无法弄清楚如何打破它。

1 个答案:

答案 0 :(得分:0)

开关循环:不应该这样写。

输入“commandInput”应该在

上循环

正确的陈述是:switch(commandInput)

你已经给变量quit一个值“。”这会导致编译器不能进入循环,因为条件永远不会满足,因为你总是要求commandInput变量作为输入 因此,当您调试代码时,您实际上会发现未输入循环,这就是循环无限的原因