2015-11-07 97 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