I'm trying to read user integer input with the following code. I'm aware that strtol returns a long value.
long color = 1;
char buf[256];
char * last;
while(color != 0){
printf("Enter a color (0 to stop): ");
fgets(buf, 256, stdin);
color = strtol(buf, &last, 10);
if(last != '\0'){
printf("You didn't enter a number.\n");
}
else{
printf("%d\n", color);
}
}
I tried running this, first entering 4, which gave me You didn't enter a number.
I tried it again with "forty" and got the same result. What am I missing here? All I want to do is get basic user input for an integer value that verifies only an integer was entered. I don't need a long because the values will all be between 3000 and 4000.