我正在实现一个表达式计算器,用户可以在其中输入带有 0b 前缀的二进制数。我希望能够(使用字符串迭代器)提前查看表达式中 0 之后的下一个字符是否是 b,如果是,则不通过那个 b 字符并将字符返回到0 在前缀的开头(类似于 ungetc)。有没有办法取消字符串中已传递的字符?
我尝试过的:
Token::pointer_type Tokenizer::_get_number( Tokenizer::string_type::const_iterator& currentChar, Tokenizer::string_type const& expression )
{
assert( isdigit( *currentChar ) && "currentChar must pointer to a digit" );
Integer::value_type const MAX_UNSIGNED_D10 = (std::numeric_limits<Integer::value_type>::max()-10)/10;
Integer::value_type accumulator = *currentChar++ - '0';
//Binary Numbers
if( *currentChar == '0' )
{
if( *currentChar++ == 'b' )
{
BinaryInteger::value_type binAccum = _get_binary( currentChar, expression );
return make<BinaryInteger>( binAccum );
}
}
}
Token::pointer_type Tokenizer::_get_number( Tokenizer::string_type::const_iterator& currentChar, Tokenizer::string_type const& expression )
{
assert( isdigit( *currentChar ) && "currentChar must pointer to a digit" );
Integer::value_type const MAX_UNSIGNED_D10 = (std::numeric_limits<Integer::value_type>::max()-10)/10;
Integer::value_type accumulator = *currentChar++ - '0';
std::stringstream iss( expression );
//Binary Numbers
if( iss.get() == '0' )
{
if( iss.get() == 'b' )
{
BinaryInteger::value_type binAccum = _get_binary( currentChar, expression );
return make<BinaryInteger>( binAccum );
}
}
}
也曾尝试使用 [] 访问字符串表达式的字符本身,但这在某些情况下非常有限。
最佳答案
当您在迭代器上调用 ++
运算符时,它会将迭代器推进到下一个元素。要在不推进迭代器的情况下查看下一个元素,您可以改用 +1
,例如:
if( *currentChar == '0' )
{
if( *(currentChar+1) == 'b' )
{
BinaryInteger::value_type binAccum = _get_binary( currentChar+2, expression );
return make<BinaryInteger>( binAccum );
}
}
请注意,如果 currentChar
在您查看之前已经位于字符串的末尾。当前元素之后的下一个元素将是字符串的 end
位置,您不应取消引用该迭代器值。您可能需要考虑向分词器添加一个额外的参数,以便它可以检测到何时到达输入字符串的末尾并且不会重复太远。
关于c++ - 如何在不通过该字符的情况下向前看一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20340366/