I'm trying to get an integer number from command line without scanf()
but using justfgets()
, how can I filter the fgets() contents
reporting an error if I insert a character or a string? The problem is that when I insert something different like a character or a string the atoi()
function (essential to do some operations in my algorithm) converts me that string to 0, whilst I'd prefer to exit if the value inserted is different from an integer.
Here's a code part:
.....
char pos[30];
printf("\n Insert a number: ");
fgets (pos, sizeof(pos), stdin);
if (atoi(pos) < 0) //missing check for string character
exit(1);
else{
printf ("%d\n", atoi(pos)); //a string or character converted through atoi() gives 0
}
int number = atoi(pos);
......
I solved on my own using strcspn()
before checking through isdigit()
the integer type, without strcspn() it'd have returned always -1