fflush() function not working with stdin

允我心安 提交于 2019-12-02 08:54:32

问题


I'm sorry for this silly question. I have C program to prompt user to enter age and name and then print the age and name to the screen. This is my exercise that I read from book.

This the program:

#include <stdio.h>

int main (void) {
   int age;
   char name[20];

   puts("Enter your age:");
   scanf("%d",&age);

   fflush(stdin);

   puts("Enter your name:");
   scanf("%s",name);

   printf("Your age is %d\n",age);
   printf("Your name is %s\n",name);

   return 0;
}

When I enter extra characters to the first scanf() the program terminates and assign the extra characters to the next scanf()

And then I changed the code, and add function named clear_buff() and using the fgets function within the clear_buff() to read the remaining characters on stream.The code work as I expected.

#include <stdio.h>

#define MAXLEN 80

void clear_buff(void);

int main (void) {
  int age;
  char name[20];

  puts("Enter your age:");
  scanf("%d",&age);

  clear_buff();

  puts("Enter your name:");
  scanf("%s",name);

  printf("Your age is %d\n",age);
  printf("Your name is %s\n",name);

  return 0;
}

void clear_buff(void){
   char junk[20];
   fgets(junk,MAXLEN,stdin);
}

My question is why fflush(stdin) not working in this program?

The book says that fflush function clear any buffered data on the stream.And I know that fflush() function is the C standard function if working with I/O stream.


回答1:


fflush is meant to work with output or update streams and using it with an input stream is undefined behavior, from cppreference C section for fflush:

The behavior is undefined if the given stream is of the input type or if the given stream is of the update type, but the last I/O operation was not an output operation.

undefined behavior is behavior that the standard does not specify and it means that the result of your program is unpredictable, which could mean behavior that seems normal or a crash or other undesirable effects.

cppreference is consistent with the language in the draft C99 standard section 7.19.5.2 The fflush function which says:

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

Although this is not really your question and it seems like you have figured out a work-around, the question C, flushing stdin covers some proper ways of flushing stdin.



来源:https://stackoverflow.com/questions/26446297/fflush-function-not-working-with-stdin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!