stringstream 和 str 不同步 [英] stringstream and str not synchronized
问题描述
我正在用 C++ 编写一个简单的解析器.我想用 std::ws
删除前导空格.
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);
}
输出是:
Before : str=[ something], peek=[ ]
After : str=[ something], peek=[s]
我不明白为什么流和流中的 str 不同步.它不应该影响 str 吗?
I don't understand why the stream and the str from the stream are not synchronized. Is it not supposed to affect the str ?
推荐答案
字符串流有一个指针,即输出位置指示符,它指向下一个"字符.通过修剪前导空白,后备缓冲区本身不会被修改,但是这个位置指示器会增加.std::ws 读取一个字符直到它变成一个空格,因此你最后一次查看会发现这个指示符指向 s
.
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
.
这篇关于stringstream 和 str 不同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!