1

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.

john
  • 85,011
  • 4
  • 57
  • 81
  • 1
    Why do you think they do the same thing? The first prints a string to standard output, one character at a time, and the second extracts characters from a stringstream. – Stephen Newell Sep 28 '20 at 06:23
  • 1
    Those don't look equivalent to me. I'd use a while loop for the second, the for loop just looks wrong. – Retired Ninja Sep 28 '20 at 06:23
  • @StephenNewell, yes that is true but they do use different methodology, but they seem to have the same outcome. I want to know the cases where the two might behave differently. – hashmalkani Sep 28 '20 at 06:26
  • Setting aside for a minute the user of the `stringstream` isn't needed, at the core of a range-based for loop is simply the use of iterators over each of the objects in a container. Which in essence both of your snippets do. The semantics will be slightly different (and in the second case you are reading 2-characters per-iteration), but underlying it all will be some iterator going from `.begin()` up to `.end()`. – David C. Rankin Sep 28 '20 at 06:27

1 Answers1

3

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.

john
  • 85,011
  • 4
  • 57
  • 81