-2

I've tried

#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 == '\0')){ //check validity here
       printf("invalid\n");
       printf("try again\n"); //type anther value
    else{
       printf("valid\n");
}

What's wrong with my code?
Is that the correct way to check integer input?

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Josephin
  • 11
  • 2

1 Answers1

0

Wrong test and function name

// if ((end == msg) || (*end == '\0')){ //check validity here
if ((end == msg) || (*end !== '\0')){ //check validity here
  printf("invalid\n");

Better to assign to long or not at all

// int input = strol(msg, &next,10);
long input = strtol(msg, &next,10);
or 
strtol(msg, &next,10);

Use errno is one wants to also check for overflow.

errno = 0;
strtol(msg, &next,10);
if (errno == ERANGE) {
  puts("Overflow");
} else    
  ...
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256