Tuesday, July 14, 2009

In c++ how can i read spaces in strings using the >> operator?

example :


the user input is: "firstName lastName"

In c++ how can i read spaces in strings using the %26gt;%26gt; operator?
Setting skipws in your istream will let you do what you want:





string a, b;


cout %26lt;%26lt; "enter two words: ";


cin %26gt;%26gt; skipws %26gt;%26gt; a %26gt;%26gt; b;


cout %26lt;%26lt; a %26lt;%26lt; "," %26lt;%26lt; b %26lt;%26lt; endl;





skipws is set for cin by default, so unless you set noskipws for cin, you could get the same result with:


cin %26gt;%26gt; a %26gt;%26gt; b;





A more general purpose technique is to use getline:





string s;


cout %26lt;%26lt; "enter string: ";


getline(cin,s);


cout %26lt;%26lt; s %26lt;%26lt; endl;





so you get the whole string, with any number of words. Then, of course, you have to do some work to parse it.

elephant ear

No comments:

Post a Comment