如何检查输入是否为字符并显示它是"invalid input",否则它将按原样运行


#include<stdio.h>
#include<string.h>
#include<stdlib.h.>
#include<locale>
using namespace std;
main()
{
int b;
printf("Enter a number:");
scanf("%d",&b);
char a = b;
if (a >= 'a' || a <= 'z' || a >= 'A' || a <= 'Z' )
{
printf("Invalid input");
}
if(int b=a || b<=0)
{
printf("It's a Negative number");
}
else if(int b=a || b>0)
{
printf("It's a Positive number");
}
else if(int b=a && b==0)
{
printf("It's a Zero");
}
}

布尔逻辑很接近,但略有误解。

您需要检查ANDzORAANDZ 之间的值是否存在无效输入。

一旦你知道ASCII表示不对字母进行编码,你就可以转换为int并做常规的数学逻辑来检查它是否为正,负,等等......

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<locale>
using namespace std;
main()
{
char b;
printf("Enter a number:");
scanf("%c",&b);
// checking ASCII value of b isn't between a AND z OR A AND Z
if ((b >=  'a' && b <= 'z') || (b >=  'A' && b <= 'Z'))
{
printf("Invalid inputn");
} else {
// convert ASCII representation to the actual int it encodes
int a = b - '0';
if(a<0)
{
printf("It's a Negative numbern");
}
else if(a>0)
{
printf("It's a Positive numbern");
}
else if(a==0)
{
printf("It's a Zeron");
}
}
}

相关内容

最新更新