阅读char和在C号
问题描述:
我试着去阅读一个字符和数字改为:阅读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)时会打印“失败”,以及为什么只有输入数字才会打印。
答
你的代码很好,除了一个;试试这个它的工作原理:
#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
}
}
我没有收到消息输入'+ 100'。 http://melpon.org/wandbox/permlink/ZksV4WifjT6y81dC – MikeCAT
'1'是一个字符。 – Olaf
打印“失败”时应检查“c”的值。这将成为阅读内容的线索。 – MikeCAT