Header file:
stdio.h
Synopsis:
int fflush(FILE *stream);
Description:
For output streams, fflush() makes any buffered unwritten data to be written. And the behavior is undefined for input stream. fflush(NULL) flushes all output streams. Returns 0 on success. Otherwise, EOF is returned.
fflush function C example:
/* Please try this program in Turbo C to get the exact output */
#include<stdio.h>
#include<string.h>
int main() {
char ch1, ch2;
printf("Enter your 1st character:\n");
scanf("%c", &ch1);
/* flushes standard i/p. So the \n will get flushed */
fflush(stdin);
printf("Enter your 2nd character:\n");
scanf("%c", &ch2);
printf("ch1:%c\tascii of ch1:%d\n", ch1, ch1);
printf("ch2:%c\tascii of ch2:%d\n", ch2, ch2);
return 0;
}
Output:
jp@jp-VirtualBox:~/cpgms/exp$ ./a.out
Enter your 1st character:
a
Enter your 2nd character:
Enter your 1st character:
a
Enter your 2nd character:
b
ch1:a ascii of ch1:97
ch2:b ascii of ch2:98
ch1:a ascii of ch1:97
ch2:b ascii of ch2:98
In the above program, fflush() flushes the input stream('\n' newline character is wiped off).
Lets rewrite the above program without fflush(stdin) and check the output.
Lets rewrite the above program without fflush(stdin) and check the output.
#include<stdio.h>
#include<string.h>
int main() {
char ch1, ch2;
printf("Enter your 1st character:\n");
scanf("%c", &ch1);
printf("Enter your 2nd character:\n");
scanf("%c", &ch2);
printf("ch1:%c\tascii of ch1:%d\n", ch1, ch1);
printf("ch2:%c\tascii of ch2:%d\n", ch2, ch2);
return 0;
}
Output:
jp@jp-VirtualBox:~/cpgms/exp$ ./a.out
Enter your 1st character:
a
Enter your 2nd character:
ch1:a ascii of ch1:97
ch2:
ascii of ch2:10
Here, ch2 takes '\n' as its input and the same is printed on the output screen.
No comments:
Post a Comment