tags:

views:

72

answers:

2

I'm a bit confused by the results of the following function:

int main() {
string command;
while(1) {
    cin >> command;

    if(command == "end")
            return 0;
    else
            cout << "Could you repeat the command?" << endl;
}

return 0;

}

First of all - the output line ("could you...") repeats once for each individual word in the input (stored in command). So far as I can see, it should only be possible for it to happen once for each instance of the loop.

Also, when the line 'if(command == "end")' is changed to 'if(command == "that's all")' it never triggers. A little testing suggested that all of the whitespace was removed from the command.

Could someone explain to me what's going on here?

Thanks

+5  A: 

The formatted input operator >>() reads space separated tokens from input. If you want to read whole lines, use the getline() function:

string command;
getline( cin, command );
anon
Thanks, that works perfectly. Out of curiousity, what does the 'cin' refer to in the getline function? What alternatives parameters could getline take for the first argument?
wyatt
Any inputstream you like. It could be data in memory, a database, a network connection anything.there is also a cin.getline() member function
Martin Beckett
@wyatt cin is an object of type istream which encapsulates access to your program's standard input. You could replace it with any object of type istream (or of a derived type) such as a file stream.
anon
+2  A: 

Most (possibly all) operating systems buffer input. When you type a string of words and then hit [enter] it is only at the time you hit enter that the input is usually passed to your program. Thus that is when it will start reading the input and separating it out into individual words (because as Neil mentions, the >> reads words, not lines). Thus your program goes through the loop multiple times (once per word you had in the line) even though you only hit enter once.

So, you are correct when you think it should only display "could you..." once per loop. That is what is happening.

Likewise, you'll never have a command that contains more than one word because of the space delimiter. As mentioned, use getline() to retrieve the entire text for the line you entered.

Noah Roberts