2015-11-07 55 views
1

我試着去閱讀一個字符和數字改爲:閱讀char和在C號

char c; 
char plus = '+'; 
int last; 
if(scanf("%c%d",&c,&last)!=2 || last<0){ 
     printf("fail\n"); 
     return 1; 
}; 

//trying to test it 
if(plus==c){ 
    // code 
} 

但是當我啓動該程序,然後鍵入+ 100,它拋出「失敗」,因爲scanf函數WASN沒有成功。但如果我只輸入100就可以了。爲什麼在有一個字符(+)和數字(100)時會打印「失敗」,以及爲什麼只有輸入數字纔會打印。

+1

我沒有收到消息輸入'+ 100'。 http://melpon.org/wandbox/permlink/ZksV4WifjT6y81dC – MikeCAT

+0

'1'是一個字符。 – Olaf

+0

打印「失敗」時應檢查「c」的值。這將成爲閱讀內容的線索。 – MikeCAT

回答

1

你的代碼很好,除了一個;試試這個它的工作原理:

#include <stdio.h> 

int main() 
{ 
    test(); 
} 

int test() 
{ 
    char c; 
    char plus = '+'; 
    int last; 
    if (scanf("%c%d", &c, &last) != 2 || last < 0) 
    { 
    printf("fail\n"); 
    return 1; 
    } ///////////// YOU HAD UNNEEDED ; HERE 
    else 
    { 
    printf("\nyou entered:\n%c,%d", c, last); 
    getchar(); 
    } 
    //trying to test it 
    if (plus == c) 
    { 
// code 
    } 
} 
+0

哪個';'你指的是?爲什麼你在'scanf()'中的'%c%d'之前添加了一個空格? 'main()'函數也沒有'return'。 – Pawan

+0

@Pawan我在代碼中添加了註釋並刪除了scanf中的空間,這只是我的一個糟糕(良好)習慣。 – BobRun