1
votes

I am capturing video from my webcam and if the user hits the Enter key I take a picture. Then I ask "Is the picture okay?" to user and wait for an input. If he says "No", I keep doing the same thing, until he says "Yes".

But if he says "No", and in the meantime I type something in the terminal, getline() function writes whatever I type into its buffer, and when I ask the question again it goes directly to "invalid input" state.

How do I prevent this?

I have read a lot of questions regarding this and I tried to use cin.ignore() and cin.clear() before/after after I call getline(), but they didn't help.

    // Do capturing here
    string choice;    
    int choiceIsOkay = 0;
    while (choiceIsOkay == 0)
    {
        cout << "Is the picture okay? (Y/N): "; 
        getline(cin, choice);

        if ((choice == "Y") || (choice == "y"))
        {
            choiceIsOkay = 2;
        }

        else if ((choice == "N") || (choice == "n"))
        {
            choiceIsOkay = 1;
        }

        else
        {
            cout << "\nInvalid input\n";
            choiceIsOkay = 0;
        }
    }

if (choiceIsOkay == 2)
{
    runAlgorithm = 1;
    break;
}

else choiceIsOkay = 0;
1
This is to be expected. Why are you typing stuff when your program expects only ENTER and Y/N input? - DĂșthomhas
@DĂșthomhas by "mistake". I would like to take every precaution. - massakrienen
Ah, okay. There isn't much you can do about that except require your users to pay attention to what they type. You could just ignore anything except the last 'Y' or 'N'. - DĂșthomhas

1 Answers

0
votes

If I understand your issue, if user enters Some Random Text In, your program always jump in "Invalid input" and never stops to wait for users input. Following code should resolve your issue.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int runAlgorithm;
    // Do capturing here
    int i = 0;
    while (i++ < 3)
    {
        int choiceIsOkay = 0;
        string choice;
        while (choiceIsOkay == 0)
        {
            cout << "Is the picture okay? (Y/N): ";
            getline(cin, choice);

            if ((choice == "Y") || (choice == "y"))
            {
                choiceIsOkay = 2;
            }

            else if ((choice == "N") || (choice == "n"))
            {
                choiceIsOkay = 1;
            }

            else
            {
                cout << "nInvalid inputn";
                choiceIsOkay = 0;
            }

            // Ignore to the end of line
            cin.clear();
        }
    }

    return 0;
}