2012-02-18 72 views
3

我有C代码做一些计算(我认为与我的问题无关)。该程序将要求一些参数进行计算。问题是当我运行代码时,scanf(“%c”,& ch)工作不正常。scanf()不带任何输入

我对是否可以重现此问题感兴趣,因为它似乎没有出现任何问题,是吗?

我发布了一个可编辑和缩短版本的程序。

#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 2012-02-18 23:06:44

+0

@ x0n:我会更加担心振动:-) – thkala 2012-02-18 23:08:44

回答

4

scanf()不消耗后换行。跳过的scanf()接收用户输入的以前线换行和终止没有收到你所期望的更多的输入...

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

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

+0

所以你的意思是把它改为printf(“请指定你的轴是弯曲(B)还是扭转(T)\ n”);?我试过,但仍然是同样的问题 – YankeeWhiskey 2012-02-18 23:07:19

+0

@YankeeWhiskey:如果你错过了,我已经编辑了几个可能的解决方案我的答案... – thkala 2012-02-18 23:36:53

+0

谢谢。我看到了。 – YankeeWhiskey 2012-02-18 23:59:07

4

由于thkala告诉上面scanf()不消耗尾随newlines.But有从使用\nscanf("%c\n",...)前一行吸收新行的另一种方式。

+0

使用'%* c'来读取一个字符而不分配任何结果。 – 2014-11-22 09:02:36