默认内部开关立即关闭

  • 本文关键字:内部 开关 默认 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');

这是其中的一部分。如您所见,我的程序应该询问用户是否要重试。它几乎适用于所有内容,但开关中的默认值除外,它会立即关闭,而不是询问我是否要重试。我是有某种误解还是什么?

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

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

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

延伸阅读:为什么我们在读取输入后调用cin.clear()和cin.ignore()?

最新更新