I type this code to make a condition on user doesn't enter a string but only numbers but when enter something like this: 55ST, program accepts 55 and don't consider 55ST a string.
printf("Enter the deposit amount L.E :");
if (scanf("%lf", &money) != 1)
{
printf("Invalid input. Please enter a number.\n");
while (getchar() != '\n')
TypeTransaction = 1;
continue;
}
I need user to enter number only. When user enter something like this: 55SSYTF, I want to stop him.
scanf
is not the best tool for this, you can use fgets
+ strtol
functions:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main()
{
long number;
char buffer[100];
char *end;
puts("enter a number:");
if (!fgets(buffer, sizeof buffer, stdin))
{
puts("can't read input");
return 0;
}
/* from comment : strtol need errno to be clear (see man) */
errno = 0;
number = strtol(buffer, &end, 10);
if ((0 != errno) || (end == buffer) || (*end && *end != '\n'))
{
puts("can't decode input");
}
else
{
printf("Number:%ld.\n", number);
}
}