2012-02-18 29 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

+0

@ x0n:私は振動について心配しています:-) – thkala

答えて

4

scanf()は改行を末尾に消費しません。スキップされたscanf()は、ユーザーが入力した前のラインから改行を受け取り、あなたが期待するよう複数の入力を受信せずに終了...

scanf()は改行と少し面倒です。可能な解決策は、fgets()を使用してコンソールから回線を取得し、次にsscanf()を使用して受信した文字列を解析することです。

最後に、scanf()コールの書式文字列に" %c"を使用すると、よりターゲットを絞った解決策が得られます。 %cフォーマット指定子は、独自の空白を消費しないため、ユーザが入力した文字ではなく、残りの改行を取得します。

+0

これはprintf( "あなたのシャフトが曲げ(B)かねじり(T)のどちらであるかを指定してください\ n"));私は同じ問題を試しましたが、まだ同じ問題があります – YankeeWhiskey

+0

@ YankeeWhiskey:あなたがそれを見逃した場合には、私は可能な解決策のいくつかを使って私の答えを編集しました... – thkala

+0

ありがとう。分かった。 – YankeeWhiskey

4

thkala としては、末尾消費しないscanf()上語っnewlines.Butそのscanf("%c\n",...)よう\nを使用して、前の行から改行を吸収する別の方法があります。

+0

文字に結果を代入せずに文字を読むには '%* c'を使います。 –

0

あなたはまた、

scanf(" %c",&c); 
関連する問題