-1

Consider the following code:

#include <iostream>

using namespace std;

int main()
{
    char input;
    while (1) {
        cout << "Enter: ";
        cin.get(input);
        cin.ignore(100, '\n'); //requires another `enter`
    }
    return 0;
}

I want to get the next character in the input buffer, and I want that input buffer to be cleared afterwards. I know that we can use cin.ignore() to do the cleaning, however, if I used it then I'll have to press enter twice (in case of inputting enter alone) to enter my input! How can I prevent that from happening?

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
Anich1935
  • 1
  • 2

3 Answers3

1
#include <iostream>
using namespace std;
int main()
{
    char input;
    while (1)
    {
        cout << "Enter: ";
        cin.get(input);
        cout << input << endl;
        cin.ignore(255, '\n');
        cin.clear();
    }
    return 0;
}

you need to clear your cin flags: cin.clear();

Axios
  • 49
  • 2
1

A workaround in this case might be to use std::string and std::getline:

#include <iostream>
#include <string>

int main()
{
    while(true)
    {
        std::cout << "Enter: " << std::flush;
        std::string input;

        if(std::getline(std::cin, input) && !input.empty())
        {
            input.front(); // this is your character
        }
    }

    return 0;
}
LogicStuff
  • 19,397
  • 6
  • 54
  • 74
  • 1
    A slight down-side to this is that it allocates memory unnecessarily. But on the up-side it is simple code. – M.M Feb 02 '16 at 09:12
0

std::cin.ignore() will block until it reads count chars or sees its delimiter. There is no reliable way to check if std::cin will block before calling an input function. The only reliable way to prevent it from blocking when input == '\n' is to check for that condition before calling ignore().

#include <iostream>
#include <limits>

int main()
{
    char input;
    while (true) {
        std::cout << "Enter: ";
        std::cin.get(input);
        if (input != '\n') {
            // Note: using std::numeric_limits<std::streamsize>::max()
            // disables std::istream::ignore's count check entirely
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }
}
Miles Budnek
  • 28,216
  • 2
  • 35
  • 52