Sami Eltamawy
Sami Eltamawy

Reputation: 9999

Check for empty line using cin

I want to check for an empty line as an input to perform a specific operation. I tried to use cin.peek() and check if it is equal to '\n', but it does not make sense.

a

b

c

empty line (here, I want to perform my action)

a

I have tried this code:

char a,b,c;
cin>>a;
cin>>b;
cin>>c;
if(cin.peek()=='\n') {
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
}

Upvotes: 2

Views: 17568

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

Use getline, then process the string. If the user entered an empty line, the string will be empty. If they didn't, you can do further processing on the string. You can even put it in an istringstream and treat it as if it's coming from cin.

Here is an example:

std::queue<char> data_q;
while (true)
{
    std::string line;
    std::getline(std::cin, line);

    if (line.empty())    // line is empty, empty the queue to the console
    {
        while (!data_q.empty())
        {
            std::cout << data_q.front() << std::endl;
            data_q.pop();
        }
    }

    // push the characters into the queue
    std::istringstream iss(line);
    char ch;
    while (iss >> ch)
        data_q.push(ch);
}

Upvotes: 6

Related Questions