scanf()
is made for formatted inputs (this is why it has an f in its name ^^). Here, your inputs are not formatted so you have to do something else.
The best way is to get the user input with fgets()
and then to check the content. As mention is a previous comment, strtol()
is the dedicated function for this task: you try to convert the string to a number and see if the conversion succeeds... or not.
Here is an example:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#define SIZE 1024
void convert() {
// Get user input
char buffer[SIZE] = {0};
printf("Enter number: ");
char* result = fgets(buffer, SIZE, stdin);
assert(result != NULL);
printf("User input = %s\n", buffer);
// Convert
char* end = NULL;
long int value = strtol(buffer, &end, 10);
if (buffer[0] == '\n') {
// The user didn't input anything
// and just hit 'enter' kit
puts("Nothing to convert");
}
else if(*end == '\n') {
// Assuming that 'buffer' was big enough to get all characters,
// then the last character in 'buffer' is '\n'.
// Because we want all characters except '\n' to be converted
// we have to check that 'strtol()' has reached this character.
printf("Conversion with success: %ld\n", value);
} else {
printf("Conversion failed. First invalid character: %c\n", *end);
}
}
int main() {
while(1) convert();
}
If you really want an int
and not a long int
, then you have to trick a little. My first idea would be to do something like this:
// Fits in integer?
int valueInt = value;
// some bits will be lost if 'value' doesn't fit in an integer
// hence the value will be lost
if (valueInt == value) {
printf("Great: %ld == %d\n", value, valueInt);
} else {
printf("Sorry: %ld != %d\n", value, valueInt);
}