永远循环...没有正确清除用户输入?

时间:2017-05-14 15:42:57

标签: c++ debugging

当用户输入“y”或“Y”表示“你想进入另一年吗?(Y / N):”时,“永久地”循环“月份为0天”。为什么? 我试着看看这些值,似乎存储的值再次被使用。也许我没有正确使用cin.clear()?

//variables
bool ucontinue = true; //answer to continue
int year = 0;
int month = 0;
int days = 0;
char answer = 'a';

//loop
while (ucontinue == true)
{
    /*
    Enter a year (Must be a positive integer): 2016
    Enter a month (Must be a between 1 and 12): 2
    The month has 29 days.
    Do you wish to enter another year? (Y/N): y
    */


    //year input
    while (year <= 0)
    {
        cout << "Enter a year (Must be a positive integer): ";
        cin >> year;
    }

    //month input
    while (month <= 0)
    {
        cout << "Enter a month (Must be a between 1 and 12):";
        cin >> month;
    }

    //# of days in the month 
    cout << "The month has " << days << " days." << endl << endl;

    //continue?
    while (answer != toupper('y') && answer != toupper('n'))
    {
        cout << "Do you wish to enter another year? (Y/N): ";
        cin >> answer;
        answer = toupper(answer);

        if (answer == toupper('n'))
        {
            ucontinue = false;
        }

    }
        cin.clear();

}

3 个答案:

答案 0 :(得分:1)

你永远编码循环,因为你在第一次运行程序时循环它工作正常但第二次绕过所有的值都设置为例如你第二次循环这个while语句

while (year <= 0)
{
    cout << "Enter a year (Must be a positive integer): ";
    cin >> year;
}

将不会运行,因为year已经大于0,并且代码中的所有while语句都会发生这种情况。如果你有while语句而不是while语句会有什么效果,因为while语句在测试条件之前会在循环中运行一次。像这样:

do
{
    cout << "Do you wish to enter another year? (Y/N): ";
    cin >> answer;
    answer = toupper(answer);


    if (answer == toupper('n'))
    {
        ucontinue = false;
    }

}while(answer != 'Y' && answer != 'N');

答案 1 :(得分:0)

如果我理解正确,请执行以下操作:

Enter a year (Must be a positive integer): 2017
Enter a month (Must be a between 1 and 12):5
The month has 0 days.

Do you wish to enter another year? (Y/N): y <ENTER>

你的程序循环。它会发生以下情况:

cin.clear();
执行

并再次启动循环。此时yearmonth仍然设置。所以当在新的循环迭代中行

while (year <= 0)
遇到

条件为false且循环继续

while (month <= 0)

对于这条线也是如此。之后

cout << "The month has " << days << " days." << endl << endl;

打印并且条件在

while (answer != toupper('y') && answer != toupper('n'))

已选中。正如我刚刚输入y这个条件不正确而且

cin.clear();
接下来执行

,此后循环无限地重新开始。

答案 2 :(得分:0)

你的程序有很多问题

  1. 你从未在days变量上更新或输入内容,所以当你在程序开头设置它时它总是为0

  2. if (answer == toupper('n'))可以缩减为if (answer=='N')