2017-05-19 26 views
0

私はこのコードを使用すると失敗します。しかし、私はcharacter.Canの誰かが私に理由を教えてくださいそれはそうです?Cで不適切なスキャン

コード:

#include <stdio.h> 

int main() 
{ 
    int a; 
    long b; 
    char c; 
    float d; 
    double e; 
    scanf("%d%ld%c", &a, &b, &c); 
    scanf("%f%lf", &d, &e); 
    printf("%d\n%ld", a, b); 
    printf("\n%c\n%.3f\n%.9lf", c, d, e); 
    return 0; 
} 

入力:

3 12345678912345 a 334.23 14049.30493 

出力:

3 
12345678912345 

0.000 
0.000000000 

それがそうであるのはなぜ?

+2

あなたは 'scanf'呼び出しで読んでいる要素の間にスペースが必要です。また、CではなくC++。 – AntonH

+0

これにはいくつのダブがあるのだろうか? – ThingyWotsit

+1

''%c ''が実際にCのロングタイプをスキャンした直後に '' space' * ''文字を読み込んだのだろうか? –

答えて

0
c  Matches a sequence of characters whose length is specified by 
      the maximum field width (default 1); the next pointer must be a 
      pointer to char, and there must be enough room for all the char‐ 
      acters (no terminating null byte is added). The usual skip of 
      leading white space is suppressed. To skip white space first, 
      use an explicit space in the format. 
3 12345678912345 a 334.23 14049.30493 
       ^

あなたのコード内で%cは "12345678912345" に続く最初の空白文字と一致します。その結果、 "a"は%fと一致したままになります。これは一致しないので、2番目のscanf()呼び出しは失敗し(一致しない場合は0を返します)。

RETURN VALUE 
     These functions return the number of input items successfully matched 
     and assigned, which can be fewer than provided for, or even zero in the 
     event of an early matching failure. 

として、あなたは%cの前に、フォーマット文字列にスペースを追加する場合は、あなたの問題が消える、上記のコメントで指摘 - それは、「A」に空白や試合をスキップします。ポインタが 'a'を越えて移動し、2番目のscanfが正しく動作します。

int number_matched; 
number_matched = scanf("%d%ld %c", &a, &b, &c)