C ++:在`get()`之后调用`unget`的异常行为>> [

问题描述 投票:0回答:1
问题:

根据以下unget()的一系列操作,在我对cin的理解中遇到了“意外”行为:

    呼叫cin.get()。假设返回a
  1. 呼叫cin.unget()。放回a
  2. 呼叫cin.get()
  3. 再次
  4. 。这将再次返回a呼叫cin.unget()
  5. 再次
  6. 。我认为这会放回a
    调用cin.peek()来检查步骤4中的unget
  7. 我希望它是a,但是它是EOF(可能是failbit)。
  8. ] >将第4步更改为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()。这放回去。 ...
c++ get stream istream
1个回答
0
投票
使用gcc版本9.3.0(Ubuntu 9.3.0-10ubuntu2)。

a get: a unget: 97 get: a unget2: 97 extract2: a

© www.soinside.com 2019 - 2024. All rights reserved.