如何从字符串流中的相同位置读取两次?

def*_*ult 3 c++ stringstream

我有一个stringstream我正在阅读的实例.在从流中获取数据的某个点上,我需要读取可能存在或不存在的标识符.逻辑是这样的:

std::string identifier;
sstr >> identifier;
if( identifier == "SomeKeyword" )
    //process the the rest of the string stream using method 1
else
   // back up to before we tried to read "identifier" and process the stream using method 2
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现上述逻辑?

Rem*_*eau 5

使用流tellg()seekg()方法,例如:

std::string identifier;
std::stringstream::pos_type pos = sstr.tellg();
sstr >> identifier;
if (identifier == "SomeKeyword")
{
    //process the rest of the string stream using method 1
}
else
{
    // back up to before we tried to read "identifier
    sstr.seekg(pos);
    // process the stream using method 2
}
Run Code Online (Sandbox Code Playgroud)

  • 注意:从C++ 11开始,`seekg()`在执行它之前清除EOF位,但是在C++之前,它会禁止搜索.所以旧平台要小心.如果下一项是一个10k字符的MIME数据块,那么"重新读取"​​方法中也存在潜在的效率问题. (3认同)