C 为什么在用户输入第一个命令后,我会将此消息打印两次?

C 为什么在用户输入第一个命令后,我会将此消息打印两次?,c,printf,C,Printf,我已经写了所有的代码,一切都是正确的,但由于某种原因,消息“Enter command或Enter'Q'to quit:”在输入第一个命令后会打印两次 我只是需要你帮我弄清楚为什么那条信息总是被打印两次。我和我的导师一起研究过这个问题,但我们似乎不明白为什么在第一次输入/命令之后,该消息会被打印两次。任何帮助他都将不胜感激 这是我的密码: int main() { studentType s[MAX_STUDENTS]; teacherType t[MAX_TEACHERS];

我已经写了所有的代码,一切都是正确的,但由于某种原因,消息“Enter command或Enter'Q'to quit:”在输入第一个命令后会打印两次

我只是需要你帮我弄清楚为什么那条信息总是被打印两次。我和我的导师一起研究过这个问题,但我们似乎不明白为什么在第一次输入/命令之后,该消息会被打印两次。任何帮助他都将不胜感激

这是我的密码:

int main() {
   studentType s[MAX_STUDENTS];
   teacherType t[MAX_TEACHERS];
   char input[MAX_NAME];
   int numS, numT;
   char command;
   FILE * out;

   numS = readStudentInfo(s); /* Number of students equals size of array. */
   numT = readTeacherInfo(t); /* Number of teachers equals size of array. */

   out = fopen("log.out", "w");

   while (command != 'Q') {
      printf("Enter command or enter 'Q' to quit:\n");
      scanf("%c", &command);

      if (command == 'S') {
         scanf("%s", input);
         fprintf(out, "-->%c %s\n", command, input);
         getStudentInfo(s, t, input, numS, numT, out);
      }

      if (command == 'T') {
         scanf("%s", input);
         fprintf(out, "-->%c %s\n", command, input);
         findStudents(s, t, input, numS, numT, out);
      }

      if (command == 'G') {
         scanf("%s", input);
         fprintf(out, "-->%c %s\n", command, input);
         getGradeList(s, t, atoi(input), numS, numT, out);
      }

      if (command == 'L') {
         scanf("%s", input);
         fprintf(out, "-->%c %s\n", command, input);
         findGradeTeachers(s, t, atoi(input), numS, numT, out);
      }

   }

   if (command == 'Q') {
      fprintf(out, "-->%c\n", command);
      fclose(out);
      return 0;
   }

   return 0;
}
下面是我运行程序时得到的结果:


正如您所看到的,只有在启动时消息“Enter…”才不会打印两次,为什么会发生这种情况?提前感谢所有回答问题的人

scanf()
的每个字符串格式的开头添加空格:

在您的代码中,换行符被捕捉到
scanf(“%c”,&command)
并且您必须通过在scanf的字符串格式的开头添加空格来避免捕捉换行符

scanf("%c",&command);
如果您输入一个字符,请说“L”,然后按enter键进入上述扫描。命令变量中只读取字符“L”,而stdin中仍然存在“回车键”。因此,下一次对于scanf,上面的enter键作为输入被feed,代码将忽略它

因此,在
%c

scanf(" %c",&command);

您还可以使用
fflush()
在扫描google之前关于
fflush()

你应该使用fflush(stdin);在scanf声明之前,感谢您的回答!我试试看!
scanf(" %c",&command);