在c中读取字符和数字

在c中读取字符和数字,c,scanf,C,Scanf,我正在尝试读取具有以下内容的字符和数字: 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 } charc; char plus='+'; int last; 如果(scanf(“%c%d”、

我正在尝试读取具有以下内容的字符和数字:

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
}
charc;
char plus='+';
int last;

如果(scanf(“%c%d”、&c和&last)!=2 | | last您的代码除了a之外没有问题;请尝试以下方法:

 #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
  }
}
#包括
int main()
{
test();
}
int测试()
{
字符c;
char plus='+';
int last;
如果(scanf(“%c%d”,&c,&last)!=2 | | last<0)
{
printf(“失败\n”);
返回1;
}//你不需要;这里
其他的
{
printf(“\n您输入的:\n%c,%d”,c,最后一个);
getchar();
}
//试着测试一下
如果(加==c)
{
//代码
}
}

我没有收到输入
+100
的消息。打印“fail”时,你应该检查
c
的值。它将成为读取内容的线索。c的值实际上是零,last的值是一些随机数(我猜是内存地址?),但没有什么可以做这样的事情。“实际上是零”?没有意义。在
c
中,在典型环境中应该有一个介于-128和127之间或0和255之间的数字。最后一个
上的随机数应该是因为它未初始化且无法读取。可能还应该检查
scanf
的返回值。它是
1
0
EOF
?whi你指的是ch
吗?为什么你在
scanf()
中的
%c%d
之前添加了一个空格?对于
main()
函数也没有
返回值。@Pawan我在scanf中添加了注释并删除了空格,这只是我的一个坏(好)习惯。