Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What exactly empty input means for cin.get()?

I think it’s a simple question, but I don’t understand the concept in this sample of code, mainly in the while loop:

#include <iostream>

const int ArSize = 10;
void strcount(const char * str);

int main(){
    using namespace std;
    char input[ArSize];
    char next;


    cout << "Enter text:\n";
    cin.get(input, ArSize);
    while(cin){

        cin.get(next);
        while(next != '\n')
            cin.get(next)
        
        strcount(input);
        cout << "Enter next line, empty line ends the program:\n";
        cin.get(input, ArSize);
    }

    cout << "The end\n";
    return 0;
}

...

What I understand is that the while loop continues until cin returns false. It filters out the remaining input that’s left in the buffer (because it wasn’t the size of ArSize or under, or it was – then it will just filter out the newline character) until it meets the newline character. Then it counts string’s characters (not important in this question), and then, let’s say someone just presses enter. cin.get() discards newline character in input. So if someone for example enters an empty line of text in the terminal, it reads it as ‘failed’ input and cin returns false? Because if someone proceeds to the new line, just by pressing enter, it just leaves the newline character in the buffer, and cin.get() can’t get it so it returns false. Or am I wrong?

In short – What exactly happens if you just press enter? cin.get() can’t get the input because there’s only newline in buffer and it counts it as failed input, so it returns false?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If cin.get(input, ArSize); reads no characters (i.e. the first character it encounters is a newline) it calls setstate(failbit) putting the stream into a failed state and therefore while(cin) becomes false ending the loop.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading