enter only number not collection from number and string

46 Views Asked by At

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.

2

There are 2 best solutions below

0
Mathieu On BEST ANSWER

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);
    }
}

0
chqrlie On

To ensure the user input is a line that contains the number and nothing else, you should read one line at a time with fgets() and parse it carefully, ignoring leading and trailing whitespace.

Here is a modified version:

#include <stdbool.h>
#include <stdio.h>

bool get_money(double *money) {
    char buf[80];
    printf("Enter the deposit amount L.E :");
    while (fgets(buf, sizeof buf, stdin)) {
        char x;
        if (sscanf(buf, "%lf %c", money, &x) == 1)
            return true;
        printf("Invalid input. Enter a number. Try again\n");
    }
    printf("Unexpected end of file or read error\n");
    return false;
}