我试过了
#define BUF_SIZE 256
char msg[BUF_SIZE];
printf("input? ");
while (fgets(msg,BUF_SIZE,stdin)!=NULL){
char *next;
int input = strol(msg, &next,10); //use strol
if ((end == msg) || (*end == ' ')){ //check validity here
printf("invalidn");
printf("try againn"); //type anther value
else{
printf("validn");
}
我的代码有什么问题?
这是检查整数输入的正确方法吗?
错误的测试和函数名称
// if ((end == msg) || (*end == ' ')){ //check validity here
if ((end == msg) || (*end !== ' ')){ //check validity here
printf("invalidn");
最好分配给long
或根本不分配给
// int input = strol(msg, &next,10);
long input = strtol(msg, &next,10);
or
strtol(msg, &next,10);
使用errno
是一个人还想检查溢出。
errno = 0;
strtol(msg, &next,10);
if (errno == ERANGE) {
puts("Overflow");
} else
...