iStream 不消耗字符

istream not consuming characters?

本文关键字:字符 iStream      更新时间:2023-10-16

我有一个名为"is"的字符串流,包含字符串"101a0101"。我的代码在这里:

cout << is.str() << endl;
char bit;
while (is >> bit) {
    if (bit == '0') /* do stuff */;
    else if (bit == '1') /* do stuff */;
    else break;
}
cout << is.str() << endl;

这是我的输出

output:   
101a0101
101a0101

为什么我的 istringstream 不消耗字符?

使用 str() 访问流的内容将返回缓冲区中的整个字符序列。如果需要访问流的未读子序列,可以将substr()tellg()一起使用:

std::string unread = is.str().substr(is.tellg());
std::cout << unread; // "a0101"