2015-11-04 55 views
0
#include <stdio.h> 
#include <stdlib.h> 
/* 
* GETOP -- get an integer operand; we do operation-specific checks later 
* 
* parameters: opno  the number of the operand (as in 1st, 2nd, etc.) 
* returns: int   the integer value of the operand just read 
* exceptions: none */ 

int getop(int opno) 

{ 
    int val; 
    int rv; /* value returned from scanf */ 
      /* a 
      * loop until you get an integer or EOF 
      * 
      * prompt and read a value */ 
    do{ 
     /* prompt and read a value */ 
     printf("\toperand %d: ", opno); 
     rv = scanf("%d", &val); 
     /* oops */ 
     if (rv == 0) 
     { 
      printf("\toperand must be an integer\n"); 
      /* loop until a valid value */ 
     } 
     while (rv == 0); 
      /* 
      * if it's EOF, say so and quit 
      */ 
     if (rv == EOF) 
     { 
      exit(EXIT_SUCCESS); 
     } 

    /* 
      * otherwise, say what you read 
      */ 
     return(val); 


    } 

/*當我寫rv == 0時,它一直給我一個無限循環。我寫錯了什麼,或者有另一種方法來檢查非整數,沒有程序進入無限循環? */爲什麼每當輸入一個非整數類型時都會一直有一個無限循環?

回答

2

因爲當scanf看到與其格式不匹配的輸入時,它只是停止讀取,並將無效輸入留在緩衝區中。因此,下次嘗試讀取時,您將嘗試再次讀取完全相同的無效輸入,並再次嘗試...

一個簡單的解決方案是使用fgets讀取一行,然後使用sscanf來獲取數據。

+0

好吧,我明白了。謝謝! – jadeh13

+0

或者檢查'scanf'的返回值,它會告訴你成功解析了多少個格式代碼。 – ShadowRanger

相關問題