scanf()没有任何输入

时间:2012-02-18 23:03:41

标签: 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);
}

列出了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);

3 个答案:

答案 0 :(得分:4)

scanf()不会消耗尾随换行符。跳过的scanf()会收到用户输入的上一行行中的换行符,并且会在没有收到更多输入的情况下终止...

使用换行符

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

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

答案 1 :(得分:4)

由于 thkala 告知上方scanf()不会消耗尾随换行符。但是还有另一种方法可以使用\n来吸收上一行中的换行符,就像scanf("%c\n",...)一样}。

答案 2 :(得分:0)

您也可以使用

scanf(" %c",&c);