user
user

Reputation: 301

how to avoid blank input by using getline()?

When I just press enter without input anything, getline() function also receive the blank input. How to fix it to not allow blank input(Has character and/or number and/or symbol)?

string Keyboard::getInput() const
{
    string input;

    getline(cin, input);

    return input;
}    

Upvotes: 0

Views: 3274

Answers (3)

P0W
P0W

Reputation: 47854

string Keyboard::getInput() const
{
    string input;
    while (getline(cin, input))
    {
        if (input.empty())
        {
            cout << "Empty line." << endl;
        }
        else
        {
            /* Some Stuffs */
        }
    }
}

Upvotes: 2

maditya
maditya

Reputation: 8916

You can keep re-doing the getline as long as the input is blank. For example:

string Keyboard::getInput() const
{
    string input;

    do {
      getline(cin, input);    //First, gets a line and stores in input
    } while(input == "")  //Checks if input is empty. If so, loop is repeated. if not, exits from the loop

    return input;
}

Upvotes: 3

Maroun
Maroun

Reputation: 96016

Try this:

while(getline(cin, input))
{
   if (input == "")
       continue;
}

Upvotes: 2

Related Questions