C - while 循环中的 fscanf 跳过用户输入 [英] C - fscanf in while loop skips user input

查看:35
本文介绍了C - while 循环中的 fscanf 跳过用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我运行程序,它进行打印,读取我从键盘输入的字符,切换到适当的情况,但不是返回到循环的顶部并在 fscanf 处停止以接收进一步的输入,它的行为就像它已经收到了一个新行或其他东西并切换到默认情况,返回到顶部再次循环并期待输入.我错过了什么?

So I run the program, it does the prints, reads the char I type from the keyboard, switches to the appropriate case, but instead of returning to the top of the loop and stopping at the fscanf in order to receive further input, it acts like it already received a new line or something and switches to the default case, returning to the top of the loop again and expecting input. What am I missing ?

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main () {
  char *command;
  command = malloc (2);

  while (1) {
    printf ("Type help for usage\n");
    printf ("Enter command: \n");
    fscanf (stdin,"%c",command);

    switch (command[0]) {
      case 'a':
        printf ("a\n");
        break;

      case 'h':
        printf ("help\n");
        break;

      default:
        printf ("default\n");
    }
  }
  return 0;
}

推荐答案

那是因为当你输入 a 时,你也输入了一个换行符 '\n',然后%c 在第二遍时选择换行符.

That's because when you enter a, you also type a newline '\n', and the %c picks up the newline on the second pass.

如果你分配char command[2];并使用scanf("%1s", command),你应该避免大多数问题.%s 转换说明符跳过前导空格,1 将输入限制为单个非空格字符,这应该对您有足够的帮助.

If you allocate char command[2]; and use scanf("%1s", command), you should avoid most problems. The %s conversion specifier skips leading white space and the 1 limits the input to a single non-white-space character, which should help you out sufficiently.

就个人而言,我仍然会使用:

Personally, I'd still use:

 char line[4096];

 while (fgets(line, sizeof(line), stdin) != 0)
 {
     char command[2];
     if (sscanf(line, "%1s", command) == 1)
         ...got a command...
     else
         ...failed...
 }

喜欢这种方式的一个原因是它每次都会吃掉换行符,但更重要的是,如果出现问题,您就可以在错误报告中使用整行信息.

One reason for preferring this is that it eats the newline each time, but more importantly, if something goes wrong, you've got the whole line of information to use in the error reporting.

这篇关于C - while 循环中的 fscanf 跳过用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆