为什么这个循环不起作用?

时间:2015-01-03 17:22:46

标签: c++ if-statement do-while

为什么这个循环不起作用?当答案不是y或n时,它会产生分段错误,但我认为我处理了问题并且它没有工作。如何解决这个问题,以便分段故障停止?我很困惑为什么它不会工作。

int main()
{
    string yes = "y";
    string uyes = "Y";
    string no = "n";
    string uno = "N";
    string answer = " ";    
    do
    {
        system("CLS");
        cout << "Welcome to the Red Fern Shipping Company where we ship your packages your way!\n";
        cout << "Do you want to ship a parcel? Y or N?\n";
        cin >> answer;
        do
        {
            if (answer == no || answer == uno)
            {
                cout << "Thank you! Come again!\n";
                system("PAUSE");
                return 0;
            }
            else if (answer == yes || answer == uyes)
            {
                break;
            }
            else
            {
                cin.clear();
                cin.sync();
                cout << "That answer is invalid and cannot work. Please enter a 'y' for yes or 'n' for no.\n";
            }
        } while (answer != yes && answer != uyes && answer != no && answer != uno);

    } while (answer == yes || answer == uyes);
    system("PAUSE");
    return 0;
}

2 个答案:

答案 0 :(得分:2)

“回答”的价值永远不等于是/否,如果它是'cin&gt;&gt;回答'没有在内在的做法中说明。

答案 1 :(得分:1)

问题是内循环是无限的

        do
        {
            if (answer == no || answer == uno)
            {
                cout << "Thank you! Come again!\n";
                system("PAUSE");
                return 0;
            }
            else if (answer == yes || answer == uyes)
            {
                break;
            }
            else
            {
                cin.clear();
                cin.sync();
                cout << "That answer is invalid and cannot work. Please enter a 'y' for yes or 'n' for no.\n";
            }
        } while (answer != yes && answer != uyes && answer != no && answer != uno);

循环内部变量answer不会续订。你应该插入语句

std::cin >> answer;

在这个内环中。

除了内部循环之外的一个语句,我会放置所有if语句。例如

        bool valid_answer;
        do
        {
            cin >> answer;

            valid_answer = answer == yes || answer == uyes || 
                                   answer == no || answer == uno;
            if ( !valid_answer )
            {
                cin.clear();
                cin.sync();
                cout << "That answer is invalid and cannot work. Please enter a 'y' for yes or 'n' for no.\n";
            }
        } while ( !valid_answer );


    if (answer == no || answer == uno)
    {
        cout << "Thank you! Come again!\n";
        system("PAUSE");
        return 0;
    }