简体   繁体   中英

Need help regarding cin.get and cin.putback

I am very new to programming and was looking at this bit of code, trying to understand how it works. My understanding is, that the start of each run of the while loop the program waits for an input, and if that input is allowed the loop is run. Is that correct? If it is, how come the program prints out the '$' if a '!' is typed in, seeing as how in that case the cout command in the else case is not activated?

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;
 }

Output: enter a phrase: Now!is#the!time#for!fun#! Now$isthe$timefor$fun$

Please see documentation for putback method:

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.

If the program reads a '!' character, it puts back to the stream a '$' character, which is read at the next loop iteration and printed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM