默认内部开关立即关闭

时间:2016-06-07 05:28:52

标签: c++

我正在尝试编写一个程序,通过今天输入和经过的天数来计算未来的一天。在大多数情况下,它的工作原理。然而,我偶然发现了一个小问题,过去一小时我一直坚持这个问题。

do
{
    cout << "To begin, enter today's day: " << endl << "0. Sunday" << endl << "1. Monday" << endl << "2. Tuesday" << endl << "3. Wednesday" << endl << "4. Thursday" << endl << "5. Friday" << endl << "6. Saturday" << endl;
    cin >> num1;

    while (num1 < 0 || num1 > 6)
    {
        cout << "The number must be in the range 0 to 6.\n";
        cout << "Please try again: ";
        cin >> num1;
    }

    cout << "Enter number of days elapsed after today: ";
    cin >> numdays;

    if (num1 == 0) { today = "Sunday"; }
    ... /* Similar cases from 1 - 5 */
    if (num1 == 6) { today = "Saturday"; }

    n = numdays % 7;

    switch (n)
    {
        case 0: cout << "Today is " << today << " and " << num1 << " days from now is Sunday" << endl;
            break;
        ... /* Similar cases from 1 - 5 */
        case 6: cout << "Today is " << today << " and " << num1 << " days from now is Saturday" << endl;
            break;
        default: cout << "Please enter a valid response" << endl;
    }

    cout << "Press R to try again" << endl; //Prompts the user to try again
    cin >> response;
    system("cls");
} while (response == 'R' || response == 'r');

这是其中的一部分。如您所见,我的程序应该询问用户是否要再试一次。除了交换机中的默认设置外,它几乎可以工作,它立即关闭,而不是问我是否要再试一次。我有某种误解或者是什么?

1 个答案:

答案 0 :(得分:2)

如果在为numdays提供输入时,会出现一些尾随字符,可以在response中阅读。您可以通过打印response的ascii值来确认这一点。

要解决此问题,请在阅读回复之前执行以下操作:

cin.ignore(256,'\n');  /* Ignore any lingering characters */
cout << "Press R to try again" << endl;
cin >> response;

进一步阅读:Why would we call cin.clear() and cin.ignore() after reading input?