scanf()函数没有接受任何输入。

3

我有一段与IT技术无关的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);
}

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);

2
请说明您的轴是处于弯曲还是扭转状态。 chortle - x0n
@x0n:我更担心的是震动 :-) - thkala
3个回答

4

正如thkala所说,scanf()不会消耗行尾的换行符。但是还有另一种方法可以通过使用\n来吸收前一行的换行符,例如:scanf("%c\n",...)


使用%*c读取一个字符,而不将结果分配给任何变量。 - 200_success

4

scanf()不会消耗掉尾随的换行符。被跳过的scanf()会接收到用户键入的上一行的换行符,并且像预期的那样在没有接收到更多输入时终止...

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

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


所以你的意思是将它改为 printf("请说明您的轴是弯曲(B)还是扭转(T)\n");?我尝试了,但问题仍然存在。 - YankeeWhiskey
@YankeeWhiskey:如果你错过了,我已经编辑了我的答案,并提供了几个可能的解决方案... - thkala

0

你也可以使用

scanf(" %c",&c);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接