C Programming - Library Functions - Discussion

Discussion Forum : Library Functions - Find Output of Program (Q.No. 4)
4.
What will be the output of the program?
#include<stdio.h>

int main()
{
    int i;
    char c;
    for(i=1; i<=5; i++)
    {
        scanf("%c", &c); /* given input is 'b' */
        ungetc(c, stdout);
        printf("%c", c);
        ungetc(c, stdin);
    }
    return 0;
}
bbbb
bbbbb
b
Error in ungetc statement.
Answer: Option
Explanation:

The ungetc() function pushes the character c back onto the named input stream, which must be open for reading.

This character will be returned on the next call to getc or fread for that stream.

One character can be pushed back in all situations.

A second call to ungetc without a call to getc will force the previous character to be forgotten.

Discussion:
18 comments Page 2 of 2.

Cherishy said:   1 decade ago
scanf function reads the char c from i/p stream stdin (which is the input b), ungetc(c,stdout)(get unsigned char) pushes c to stdout(the monitor), printf also pushes the char c to output screen.

ungetc(c,stdin) pushes back the char to input stream stdin...this c is read again when scanf is implemented in next loop.

Notice that ungetc can b used only for 1 byte of data...hence first use of ungetc is forgotten and the o/p is only b (as a result of printf...).

Amudhan said:   1 decade ago
Shouldn't the ungetc() have a pointer to an input stream? stdout is an output stream?

Srn said:   1 decade ago
What is the logic behind program I couldn't understand. Please help me?

Abc said:   1 decade ago
Does it mean. . Each character entered will be freed by ungetc () ?

Nayak said:   1 decade ago
What is logic to implement it?

Divya said:   1 decade ago
Hai kalidass it means the ungetc (c, stdout) function won't display the previous char.

Mahesh said:   1 decade ago
I couldn't get the logic of this o/p can anyone help me?

Kalidass said:   1 decade ago
Usually ungetc() fuctions used get a single character input,But here whenever we call the ungetc(c,stdout) it wont previous take char(i.e.,it releases from buffer or forgot the previous char)


Post your comments here:

Your comments will be displayed after verification.