What is the difference between range based loop and stringstream while extracting characters from a string

102 Views Asked by At

consider a string like string s = "xyz123".

for(char ch : s)
    cout<<ch;

and stringstream like

char ch;
stringstream ss(s);
while(ss>>ch) 
    cout<<ch;

They both give the same solution. Is there any case where the two behave differently? When should each be used.

1

There are 1 best solutions below

0
On BEST ANSWER

The second one will skip any whitespace in the string. That's how >> works.

Unless skipping whitespace is actually a requirement the second version is also unnecessary. Why construct a new object just to iterate through a string when there are methods built into string for iteration.