Search code examples
c++do-whileistringstream

do...while() repeating the last string twice


The following code splits the provided string/line down to the characters. Why does the loop repeats that last string twice? How to fix it?

#include <iostream>
#include <vector>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    string main, sub;
    cout << "Enter string: ";
    getline(cin, main);
    istringstream iss(main);
    do
    {
        iss >> sub;
        cout << sub << endl;
        vector<char> v(sub.begin(), sub.end());
        for(int i = 0; i < v.size(); i++)
         {
             cout << v[i] << endl;
         }
    } while (iss);
    return 0;
}

Input:

hello world

Desired output

hello
h
e
l
l
o
world
w
o
r
l
d

Actual output:

hello
h
e
l
l
o
world
w
o
r
l
d
world
w
o
r
l
d

I have removed elements which are unrelated to the problem as much as possible


Solution

  • In the last run, the iss raises a failure so the value of sub is not updated which causes the repeat to happen. One way to see this is to set sub to be the empty string at the start of the do loop. To avoid this kind of issue, I would do something like the following

    while(iss>>sub){
      cout<<sub<<endl;
      etc
    }
    

    Also, I would like to point out that you can iterate through a string as it can be treated as a char*, so you do not need the vector conversion stuff.