0

I have a string like "ABC DEF " with whitespace at the end. I would like to convert it into a vector of strings like {"ABC" "DEF"}, so I used a stringstream:

string s = "ABC DEF ";
stringstream ss(s);
string tmpstr;
vector<string> vpos;
while (ss.good())
{
    ss >> tmpstr;
    vpos.push_back(tmpstr);
}

However, the result vpos is {"ABC" "DEF" "DEF"}. Why the last word will be duplicated in the vector? And what is the correct code if using stringstream is required?

C. Wang
  • 2,516
  • 5
  • 29
  • 46

1 Answers1

4

ss.good() only tells you whether things have been good so far. It doesn't tell you that the next thing you read will be good.

Use

while (ss >> tmpstr) vpos.push_back(tmpstr);

Now you are reading tmpstr first and then checking the state of the stream. It is equivalent to this:

for (;;) {
    istream &result = ss >> tmpstr;
    if (!result) break;
    vpos.push_back(tmpstr);
}
Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
  • Thanks for this answer. I found the return value is of type `istream`, so I wrote `while (istream obj = ss >> tmpstr) `, but it seems wrong. So what's the syntax behind `ss >> tmpstr`? – C. Wang Aug 28 '14 at 02:38
  • Thanks for your explanation! I learned a lot. – C. Wang Aug 28 '14 at 02:43