2016-12-22 21 views
0

1 2 3 4 5のようなscanf番号を入力してEnterキーを押してコードを実行すると、while文から壊れることがあります。ここでは何もしていませんが、何も動作しません。while文からの復帰

while(1){ 
    res=scanf("%d",&x); 
     arr[i++]=x; 
     counter++; 
      if (res == 0){ 
       printf("EOF\n"); 
       break; 
      } 
      if (res != 1) 
      { 
       printf("Nespravny vstup.\n"); 
       return 1; 
      } 
      if (counter > 100) 
      { 
       printf("Nespravny vstup.\n"); 
       return 1; 
      } 
    } 
printf("Counter:%d\n", counter); 

答えて

1

のscanfのmanページによると:あなたのケースでは

NAME 
    scanf, fscanf, sscanf, vscanf, vsscanf, vfscanf 
... 

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. 

    The value EOF is returned if the end of input is reached before either 
    the first successful conversion or a matching failure occurs. EOF is 
    also returned if a read error occurs, in which case the error indicator 
    for the stream (see ferror(3)) is set, and errno is set indicate the 
    error. 

scanf早期のマッチングに失敗しの場合には0を返します。

+0

しかし、ユーザーが1 2 3を押してコードを入力し続けるとどうなるでしょうか? – blackroad

+0

ブレークするには、非数値文字( 'abcd'など)とEnterキーまたは' Ctrl + D 'キーだけを入力します –

1

戻り値は、関数全体を中断します。 break;返品の代わりに