c-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 An");
        scanf("%c", &Ch);
//      getchar();
        printf("Please input the diameter of the shaft in inchn");
        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 An");
  (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 inchn");
  (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);

scanf()不使用尾随换行符。跳过的scanf()从用户键入的前一行中接收换行符,并在没有收到更多输入的情况下终止,正如您所期望的那样。。。

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

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

Asthkala告诉上面的scanf()不使用尾随换行符。但是还有另一种方法可以像scanf("%cn",...)一样使用n从前一行吸收换行符。

您也可以使用

scanf(" %c",&c);

最新更新