Please expound on get() function mentioned in the following code.....am not able to understand the output of this program.

#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
    char ch;
    cout<<endl<<"Enter a character:";
    cin.get(ch);
    cout<<ch;
    cin.putback(ch);
    cin.get(ch);
    cout<<endl<<ch;
    int count=cin.gcount();
    cout<<endl<<"Characters extracted in last get()= "<<count;

    //stuff stream with a Z
    cin.putback('Z');
    ch=cin.peek();
    cout<<endl<<ch;

    //Z is still in stream
    cin.get(ch);
    cout<<endl<<ch<<endl;
    return 0;
}

Several things. One, what is the OS and compiler you are using? Two, please post the output you are getting. Three, what don't you understand about that output?

That said, it is crappy code, but should work OK. That said, all of the cout function calls do not have an endl or flush operator at the end of each line, so the output will be cached until the next call to one of those operators (output manipulators).

Edited 3 Weeks Ago by rubberman

thanks for your response. Following are the answers to your questions.

  1. (Which OS and compiler used?) Windows 7, using Microsoft Visual C++ 2008 Express Edition.
  2. Output of the program Output_1.jpg
  3. (What am not able to understand) When we enter a character, say P, after the prompt message, it gets collected into ch variable via the function call to get(ch) by cin object (showed in list No.9 in program) Ok, after that it is displayed on screen upon using cout<<ch (List No. 10 ), after this we are calling the putback(ch) function (No11 in the program list) which inserts last character read, back into input stream, because of which we are able to get character P again on screen using cout<<endl<<ch (No.13 in program list), here just above on No.12 we have again used cin.get(ch), why has it been used here?, if I remove it and run the program i get the following outputOutput_2.jpg
    from the above pic, How come "Character extracted in last get()=0, (equals zero???) when the get() function had collected P in the first place!!!!! also note if I remove code cin.get() (on list No.23) there is no change in the output, same as in the first attached pic (Output1.jpeg)
    help..