splitting a string into sub strings( word segments)

I have used a method called istringstream to split the string input into word segements.And it was successful.
But the problem is it displays the end word segment(last word of the last line) repetitively another two times.
eg: if the input is: Hello world this is my first c++ program.
result is:
1
2
3
4
5
6
7
8
9
10
11
12
hello
world
this
is
my
first
c++
program.
program.


program.


Note that the spaces(newlines) in line 10 and 11 are generated from the program.

can anyone give me a solution to eliminate those repetitive last word segments.

These are my code segments:

1
2
3
4
5
6
7
istringstream split(traverseLines); //splitting the lines
			while(split)
			{
			split>> wordSegments;
			cout<< wordSegments<<endl;
			}
		}
Last edited on
Try this:

1
2
3
4
while(split >> wordSegments)
{
    cout << wordSegments << endl;
}

You see, the way you do it, you print one more time after split >> wordSegments; fails. Another way to do it is this:

1
2
3
4
5
6
7
while(true)
{
    split >> wordSegments;
    if (!split) break;

    cout << wordSegments << endl;
}
Last edited on
Thanks a lot. It works. I have just understood the mistake i have done that the while loop runs one more time until condition becomes false. Its very clear in your reply and helps me a lot.

Thanks again for your help.
Topic archived. No new replies allowed.