2

I am trying to write a program that can calculate a future day by inputting today and number of days elapsed. For the most part, it works. However, I stumbled upon a tiny problem and I have been stuck with it for the past hour.

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

Here's a part of it. As you can see, my program is supposed to ask the user if he wants to try again. It works for almost everything but the default in the switch, it closes right away instead of asking me if I want to try again. Am I having some sort of misconception or what?

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
  • Once I fill in what was left out I'm unable to reproduce. Good odds I'm making different assumptions about the types of the variables than you are. – user4581301 Jun 07 '16 at 05:46

1 Answers1

2

If while giving input for your numdays, some trailing character is present, it may be read in response. You can confirm this by printing the ascii value of response.

To overcome this issue, do the following before reading in the response:

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

Further reading: Why would we call cin.clear() and cin.ignore() after reading input?

Community
  • 1
  • 1
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100