2016-06-07 103 views
2

我正試圖編寫一個程序,可以通過輸入今天和已過去的天數來計算未來日期。大多數情況下,它是有效的。然而,我偶然發現了一個小問題,並且在過去的一個小時裏我一直堅持着它。立即關閉開關內部

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

回答

2

如果在給您的輸入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?