unget()
的一系列操作,在我对cin
的理解中遇到了“意外”行为:cin.get()
。假设返回a
。cin.unget()
。放回a
。cin.get()
a
。呼叫cin.unget()
a
调用cin.peek()
来检查步骤4中的unget
。a
,但是它是EOF
(可能是failbit
)。putback(ch)
,并按我期望的方式进行get
编辑。测试程序:
/**
* Experiment on unget and get
*/
<...>
int main() {
char ch;
while (true) {
ch = cin.get();
cout << "get: " << ch << endl;
cin.unget();
cout << "unget: " << cin.peek() << endl;
ch = cin.get();
cout << "get: " << ch << endl;
/**
* Replacing below with unget gets cin in invalid state, even if extraction above is successful
*/
// cin.putback(ch);
cin.unget();
cout << "unget2: " << cin.peek() << endl;
cin >> ch;
cout << "extract2: " << ch << endl;
}
return 0;
}
设置
g++ -v Apple clang version 11.0.3 (clang-1103.0.30.11) Target: x86_64-apple-darwin19.5.0 Thread model: posix
问题:我对以下cin进行的一系列操作对unget()的理解遇到了“意外”行为:调用cin.get()。假设返回a。呼叫cin.unget()。这放回去。 ...
a
get: a
unget: 97
get: a
unget2: 97
extract2: a