getchar以错误的顺序给出输出

时间:2014-10-10 10:44:29

标签: c

程序应按以下方式提供输出:

输入字符

成功进入!

#include <stdio.h>

int main() {

  int c,d ;

  printf("Enter a character\n");
  c = getchar();
  printf("Successfully entered!\n");
  putchar(c);

return(0);

}

但是当它运行时,它等待用户在请求之前输入输入,然后以下列方式打印出来:

输入字符

成功进入!

1 个答案:

答案 0 :(得分:1)

你可以在getf之前的printf之后放一个fllush

  printf("Enter a character\n");
  fflush(stdout);
  c = getchar();

fflush意味着在输出流上调用。这是C标准的摘录:

int fflush(FILE *ostream);

ostream 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.