2016-12-06 32 views
0

當前正在完成程序開始時的程序設計,我希望用戶輸入整數作爲選擇菜單項的方式。我已經努力實現一定程度的輸入檢查,以便程序檢查輸入是否是2個菜單編號中的1個。但是,即使輸入了有效的輸入,也無法將其提取出來,程序將其識別爲無效輸入。 我的代碼如下:scanf讀入的值未按預期工作

#include <stdio.h> 
#include <math.h> 
#include <string.h> 
#define WIDTH 15 
#define HEIGHT 15 
#define NAMELENGTH 128 

int main() { 
    //int actGrid[HEIGHT][WIDTH]; 
    //int nextGrid[HEIGHT][WIDTH]; 
    char name[NAMELENGTH]; 
    printf("Welcome to Conway's Game of Life. To Begin, What Is Your Name?\n"); 
    scanf("%[^\n]%*c", name); 
    int menSelect; 
    printf("Hello %s, Please Enter the Integer Next to the Item Below That Describes How You Would Like Your Game of Life to Initially Be Set Up\n \n 1. Gosper's Glider Gun \n 2. R-Pentomino\n ", name); 
    for(;;){ 
     int checkIn=scanf("%d",&menSelect); 
     if(checkIn!=1){ 
      fprintf(stderr,"Scanf Has Failed to Read In Any Values\n"); 
     } 
     if(menSelect!=1 || menSelect!=2){ 
      fprintf(stderr,"%s, %d Is Not a Valid Selection\nPlease Try Again\n",name,menSelect); 
     }else{ 
      break; 
     } 
    } 
    return 1; 
} 

老實說,我該感到相當難倒了scanf函數顯然讀取正確的值,但隨後被處理,就好像它沒有。

回答

2

你的代碼是完美的除了||在'如果'情況下。 ||如果至少有一個條件爲真,則返回true。當menSelect等於1時,它不等於2,因此'if'條件評估爲真。使用& &解決了這個問題。如果menSelect等於1,那麼'if'條件失敗並且評估爲假

if(menSelect!=1 && menSelect!=2){ 
     fprintf(stderr,"%s, %d Is Not a Valid Selection\nPlease Try Again\n",name,menSelect); 
    } 

希望它有幫助!

+0

啊我是個傻瓜!這完美地解決了這個問題。謝謝你的幫助。 – dbr

+0

乾杯!感謝您接受答案:) – ZealousCoder