简体   繁体   中英

Stringstream weird behaviour

I don't know if this is actually weird or this is how it's supposed to be, but here's my current struggle. Suppose we have something like:

stringstream sso("12 1442 nana 7676");
double num = 0;
while(sso >> num || !sso.eof()) {
    if(sso.fail()) {
        sso.clear();
        string dummy;
        sso >> dummy;
        continue;
    }
    cout << num << endl;
}

That results in:

12
1442
7676

as expected. But if I , for example, change the string literal into 12 + 1442 nana 7676 , then I get:

12
7676

Why does the character '+' mess things up here ?

As we know now, + is a valid token for a double , so you need a way to skip to the next space-separated token instead of just getting rid of it. This function can do it for you:

template<class Ct>
std::basic_istream<Ct>& next_token(std::basic_istream<Ct>& is) {
  is.clear();
  std::ctype<Ct> const& ctype = std::use_facet<std::ctype<Ct>>(is.getloc());
  if (ctype.is(ctype.space, is.peek())) {
    return is >> std::ws;
  }
  Ct c;
  while (is.get(c) && !ctype.is(ctype.space, c)) {
    ;
  }
  return is;
}

Then you can change your code to:

stringstream sso("12 + 1442 nana 7676");
double num = 0;
while (sso) {
  if (!(sso >> num)) {
    sso >> next_token;
  } else {
    cout << num << endl;
  }
}

Output:

12
1442
7676

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM