简体   繁体   中英

stringstream and str not synchronized

I'm writing a simple parser in c++. I would like to remove leading whitespaces with std::ws .

bool            Parser::readWhiteSpace()
{
  std::cout << "Before : str=[" << this->_ss.str() << "], peek=[" << (char)this->_ss.peek() << ']'<< std::endl;
  this->_ss >> std::ws;
  std::cout << "After : str=[" << this->_ss.str() << "], peek=[" << (char)this->_ss.peek() << ']'<< std::endl;                                                                                                                                          

  return (true);
}

The output is :

Before : str=[   something], peek=[ ]
After :  str=[   something], peek=[s]

I don't understand why the stream and the str from the stream are not synchronized. Is it not supposed to affect the str ?

The string stream has a pointer, the output position indicator, which points at the "next" character. By trimming leading whitespace, the backing buffer itself is not modified, but this position indicator is incremented. std::ws reads a character until it's a whitespace, thus your last peek would find this indicator pointing to s .

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