scanf() 不接受任何输入

Yan*_*key 3 c gdb scanf

我有 C 代码做一些计算(我相信与我的问题无关)。程序会要求一些参数进行计算。问题是当我运行代码时, scanf("%c", &ch) 无法正常工作。

我感兴趣的是你是否可以重现这个问题,因为我似乎没有做错什么,不是吗?

我发布了我的程序的可编译和缩短版本。

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(void)
{
        float Dia_MM, Dia_I, Se1, Se, Sut = 75.00;
        float Ka, Kb, Kc, Kd, Ke, Kf;
        char Ch;
        char Bt;
        float Reli;
        printf("Please input the surface condition of the shaft: G, M, H or A\n");
        scanf("%c", &Ch);
//      getchar();
        printf("Please input the diameter of the shaft in inch\n");
        scanf("%f", &Dia_I);
        printf("Please specify whether your shaft is in bending (B) or torsion (T)");
        scanf("%c", &Bt);// THIS LINE IS JUST SKIPPED
        exit(0);
}
Run Code Online (Sandbox Code Playgroud)

列出GDB日志:

  Breakpoint 1, main () at main.c:25
  25        float Dia_MM, Dia_I, Se1, Se, Sut = 75.00;
  (gdb) n
  30        printf("Please input the surface condition of the shaft: G, M, H or A\n");
  (gdb) n
  Please input the surface condition of the shaft: G, M, H or A
  31        scanf("%c", &Ch);
  (gdb) G
  Undefined command: "G".  Try "help".
  (gdb) n 
  G
  33        printf("Please input the diameter of the shaft in inch\n");
  (gdb) n
  Please       input the diameter of the shaft in inch
  34        scanf("%f", &Dia_I);
  (gdb) n
  4.5
  35        printf("Please specify whether your shaft is in bending (B) or torsion (T)");
  (gdb) n
  36            scanf("%c", &Bt);
  (gdb) n                            //PROBLEM HERE. SCANF() GOES BEFORE TAKE ANY INPUT.
  37        exit(0);
Run Code Online (Sandbox Code Playgroud)

thk*_*ala 5

scanf()不消耗尾随换行符。跳过的接收来自用户输入的上一行的换行符并终止,而没有像您期望的那样接收更多输入scanf()......

scanf()换行有点麻烦。一种可能的解决方案是使用fgets()从控制台获取一行,然后sscanf()解析接收到的字符串。

" %c"另一种更有针对性的解决方案是在上次调用的格式字符串中使用scanf()。格式%c说明符本身不消耗前导空格,这就是为什么它获取剩余的换行符,而不是用户键入的字符。