c++terminalstdstringis-empty

How do I make my terminal quit on an empty cin input in c++?


I can't find a way to make my terminal quit the program on an empty input. I have:

int main(int argc, char const* argv[]) {
    // Write your code here
    // Define variables

    set<string> words;  // The set
    bool more = true;     //  Flag indicating there are more lines to read

    // If there is no command line argument, use stdin to get the lines
    if (argc == 1){

        // Take lines in until a blank line is entered
        while (more) {

            // Get next line from stdin
            string input;
            cin >> input;

                // Quit if we hit a blank line
                if (input.empty() ) {
                    more = false;
                    break;
                }

I've tried:

if (!cin )
if (input == "")
if (input == "\n")
if (input == "" || "\n")
if (input.empty())

For each of these I expected the program to take no input, or simply hitting enter, as the end of taking in inputs and quit.


Solution

  • operator>> skips leading whitespace, so it will never give you an empty string if the read is successful (which you are not checking for). You can break the stream with Ctrl-C/Z or Ctrl-Break (depending on platform) to put cin into an error state that makes statements like if (cin >> input) evaluate as false.