需要有关 cin.get 和 cin.putback 的帮助

Need help regarding cin.get and cin.putback

我对编程还很陌生,正在查看这段代码,试图了解它是如何工作的。我的理解是,程序等待输入的 while 循环的每个 运行 的开始,如果允许该输入,则循环为 运行。那是对的吗?如果是,程序怎么会在 '!' 的情况下打印出 '$'?是输入的,看看在那种情况下如何不激活 else 情况下的 cout 命令?

int main() {
 char ch;
 cout << "enter a phrase: ";
 while ( cin.get(ch) ) {
     if (ch == '!') cin.putback('$');
     else cout << ch;
     while (cin.peek() == `#') cin.ignore(1,'#');
  }
 return 0;
 }

输出:输入一个短语:Now!is#the!time#for!fun#! 现在$是 $fun$

的$时间

putback方法请见documentation

istream& putback (char c);

Put character back

Attempts to decrease the current location in the stream by one character, making the last character extracted from the stream once again available to be extracted by input operations.

如果程序读取一个 '!' 字符,它会将一个 '$' 字符放回流中,该字符在下一次循环迭代中读取并打印。