立即关闭开关内部

问题描述:

我正试图编写一个程序,可以通过输入今天和已过去的天数来计算未来日期。大多数情况下,它是有效的。然而,我偶然发现了一个小问题,并且在过去的一个小时里我一直坚持着它。立即关闭开关内部

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'); 

这是它的一部分。正如你所看到的,我的程序应该询问用户他是否想再试一次。它几乎适用于所有情况,但交换机默认情况下,它马上关闭,而不是问我是否想再试一次。我有某种误解或什么?

+0

有一次我填写了剩下了我无法重现。很可能我对变量的类型做出了与你不同的假设。 – user4581301

如果在给您的输入numdays时出现一些尾随字符,可以在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?