c++ - 如何从字符串流中的同一位置读取两次?

标签 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

如何实现上述逻辑?

最佳答案

使用流的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
}

关于c++ - 如何从字符串流中的同一位置读取两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34050729/

相关文章:

c++ - 清除并重用一个字符串流进行多次转换

c++ - stringstream code separating words - 这东西是怎么工作的?里面的代码片段

c++ - 如何检测测量水位的白色仪表板?

c++ - const 内的非 const

c++ - 为什么分配成员会引发 NullReferenceException?

c++ - luhn算法和C++中的 'digit manipulation'

c++ - 字符串流产生内存映射

c++ - 使用具有实时性能要求的 c++ STL stringstream 进行日志记录

c++ - 具有不同可能性的随机整数

c# - 关于变量名成员前缀