从命令提示符执行程序时fgets发生的问题

scanf("%d",&a); fflush(stdin); fgets(ch,SIZE,stdin); //SIZE=100 and ch is a char array 

我只使用了这部分代码。它工作正常。但是当我使用file.exe output.txt从cmnd prmpt执行此程序时,它在output.txt文件中给出了一个垃圾值。

您可以使用getcharfgetc(stdin)刷新stdin

 static void flush_stdin(void) { int c; while ((c = fgetc(stdin)) != '\n' && c != EOF); } scanf("%d",&a); flush_stdin(); fgets(ch,SIZE,stdin); //SIZE=100 and ch is a char array