when will the expression (std::cin>>buff) evaluate to false(0)?
I have been trying to take input until empty string is entered(simply press enter) ?
Is there any other way to achieve this?

Recommended Answers

All 6 Replies

Have a look at the stream operator>> here and operator! here. The extraction operator returns a reference to the stream, not a boolean value. You can check the stream state through its provided interface.

I have been trying to take input until empty string is entered(simply press enter) ?

The >> operator doesn't recognize whitespace except as a delimiter on both sides. If you just press enter, it's ignored while the >> operator waits for non-whitespace. To check for a blank line you would use getline():

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string buff;
    
    while (getline(cin, buff) && !buff.empty())
    {
        cout << "'" << buff << "'" << endl;
    }
}

But that doesn't have the same behavior as the >> operator if you want to read words instead of lines. What kind of behavior do you want for user input?

The extraction operator returns a reference to the stream, not a boolean value.

But the stream object has a conversion to boolean when in boolean context. Prior to C++11 the conversion was to void* and then to boolean from there, and in C++11 there's a direct conversion to bool.

Thanks for replying....
will the loop while(std::cin>>buff) {}
buff being a <string> variable, go on forever?

It will go on forever unless the user signals EOF or there's a stream error of some sort.

and how does user signals EOF (sorry a newbie!...)?
I suppose by pressing Ctrl+c or forcibly ending the program.
Please correct in case i am wrong.

and how does user signals EOF (sorry a newbie!...)?
I suppose by pressing Ctrl+c or forcibly ending the program.
Please correct in case i am wrong.

It depends on the operating system, but Windows uses ctrl+z and Linux/Unix-based OSes use ctrl+d. Those two are the most common; let me know if you're not using either of them.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.