string size / lenght problem

Hello,
i have problem with size() function.
Whenever i want to count how many characters have string i typed from console, i got wrong value.
The problem is that size() counts characters to first space in typed string.

in code
string strNps ="Bla bla bla"
int i = strNps.size()
integer i gets correct value (11)

but in code
string strNps;
cin>>strNps;
int i = strNps.size();
integer i gets number of characters to first space - for example for typing "Bla bla bla" int i gets value 3.

How to solve it?
closed account (z05DSL3A)
cin >> ... will only get the the text upto the first space, try getline

http://www.cplusplus.com/reference/string/getline/
Last edited on
The problem is that size() counts characters to first space in typed string.

No, it doesn't, as the first lines of your snippet demonstrate. Your problem is the >> operator. It uses whitespace as a delimiter, so cin >> strNps; reads input until it finds a whitespace and leaves the rest of the input in the stream. You want to use getline():

1
2
3
string s;
getline(cin, s)
cout << s.size() << endl;


EDIT: too slow...
Last edited on
Thanks!
Topic archived. No new replies allowed.