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;
}
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 1 of 2.
Rajesh said:
2 decades ago
I couldn't get the logic of this o/p can anyone help me?
What does ungetc(c,stdout) statement will do?
What does ungetc(c,stdout) statement will do?
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)
Mahesh said:
1 decade ago
I couldn't get the logic of this o/p can anyone help me?
Divya said:
1 decade ago
Hai kalidass it means the ungetc (c, stdout) function won't display the previous char.
Nayak said:
1 decade ago
What is logic to implement it?
Abc said:
1 decade ago
Does it mean. . Each character entered will be freed by ungetc () ?
Srn said:
1 decade ago
What is the logic behind program I couldn't understand. Please help me?
Amudhan said:
1 decade ago
Shouldn't the ungetc() have a pointer to an input stream? stdout is an output stream?
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...).
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...).
SHARMA said:
1 decade ago
I don't get above logic. Even whenever I'm running this program that time an error msg comes that is core dumped.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers