0

I am not able to understand why after reaching the last word it doesn't output blank or null character or garbage value or anything else . Why >> doesn't has any impact whatsoever after finishing the string .

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
    stringstream ss("I am going to goa for");  // Used for breaking words
    string word; // To store individual words
    while (ss >> word)
        cout<<word<<"\n";
    ss >> word;
    cout<<word<<endl;
    ss >> word;
    cout<<word<<endl;
    ss >> word;
    cout<<word<<endl;
}

OUTPUT:

I
am
going
to
goa
for
for
for
for
1
  • Your stream has an error flag set (that's why the while loop terminated), yet you still keep reading from it. Commented May 5, 2016 at 11:32

2 Answers 2

1

When >> reaches the end of the string, the failbit is set and it stops reading further.

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
    stringstream ss("I am going to goa for");  // Used for breaking words
    string word; // To store individual words
    while (ss >> word)
        cout<<word<<"\n";

    word = "END";
    ss >> word;
    cout<<word<<endl;
    ss >> word;
    cout<<word<<endl;
    ss >> word;
    cout<<word<<endl;
}

You are seeing the for because that is what stored in it. Change it to something else you will find that it doesn't read from the stringstream till failbit is cleared.

The output is:

I
am
going
to
goa
for
END
END
END

Refer stringstream for more details.

Sign up to request clarification or add additional context in comments.

Comments

0

Before every cout << word << endl; line you should add if(!ss.fail()) to check no error has occurred in the stringstream following the read attempt.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.