[cs23021] mixing getline() and extraction operator

Mikhail Nesterenko mikhail at cs.kent.edu
Tue Feb 21 18:46:53 EST 2012


CSI students,

I mentioned that you should not mix getline() function and extraction
operator in the same program. The simple advice would be to use only
getline() for your 7th lab.

However, if you decide to use both, here are more details. getline()
inputs everything to the string from the input stream until it
encounters end-of-line character (\n). getline() removes this
end-of-line character from the input stream.  Extraction operator
inputs a token and then leaves the whitespace in the input stream.

Therefore, if getline() is used right after the extraction operator
(that left the end-of-line in the input stream), then getline() might
input an empty string. For example

  string s1, s2;
  cin >> s1;         // inputs the token to "s1"
  getline(cin, s2);  // s2 is going to be empty due to leftover \n
  	       	     // if return is input after the first token

To deal with such instances, you might consider using peek() and
ignore() functions

	  peek() -- looks up the next character in the input stream
	  	    without removing it 
          ignore() -- discards the next character

For example the code above can be fixed as follows:

    string s1, s2;
    cin >> s1;
    if (cin.peek() == '\n') cin.ignore();
    getline(cin,s2);

Thanks,
-- 
Mikhail


More information about the cs23021-2 mailing list