stringstream and str not synchronized

别等时光非礼了梦想. 提交于 2020-01-06 13:59:28

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/27472658/stringstream-and-str-not-synchronized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!