c - scanf() 不接受任何输入

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

最佳答案

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

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

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

关于c - scanf() 不接受任何输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9344997/

相关文章:

c++ - 为什么 GDB 没有在断点处停止?

c - 使用 fscanf() 跳转到下一行

c++ - 格式化 IO 函数 (*printf/*scanf) 中的转换说明符 %i 和 %d 有什么区别

c - 为什么在bpf_helpers中定义了load_half,但在filter.c中却没有出现?

c - 内核模块加载导致错误

c - 如何在 Ruby C 扩展中创建 Date 对象?

C fscanf 丢弃多余的字符(如果有的话)

C - 使用 while 和 switch/case 的菜单程序返回具有无效选择的重复菜单

c++ - gdb 在完成 main 后跳转前几行

c - 汇编 - 如何找到一个函数为自己分配了多少堆栈空间