hi, i have the following codes, is there any way to check if the user entered a character instead a number? btw, i dont want to change the input type from long to char
thanks =D

long input;										
printf("enter a digit to your list: ");			
7 Years
Discussion Span
Last Post by Narue

The short answer it No -- not with scanf(). scanf() will stop processing keyboard input when the first non-digit is reached or when no more charcters in the keyboard buffer. That function does no error checking.


For this to work, you'll have to inspect each character from the stream using the isdigit() function.

Also you will have to get the input as a string and not as numeric data. If the valid checks pass (e.g. no non-digits entered) then you can easily convert the string to long.


btw, i dont want to change the input type from long to char

Do you mind an intermediate step where the input is taken as a string and then converted to long? You'd have much more control that way:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
    char line[BUFSIZ];

    printf("Enter a number: ");

    if (fgets(line, sizeof line, stdin) != NULL && line[0] != '\n') {
        char *end;
        long input;

        line[strcspn(line, "\n")] = '\0';
        errno = 0;
        input = strtol(line, &end, 0);

        if (!(errno == 0 && *end == '\0'))
            fprintf(stderr, "Invalid input [%s]\n", line);
            printf("You entered %ld\n", input);

    return 0;

That function does no error checking.

It does do error checking, and quite well too. The problem is that scanf is limited in terms of lookahead for validating the next character as well as limited in terms of determining if such a lookahead approach is even what the programmer wanted.


im not allowed to do such complicated way~~
but thx all for helping me out =D

Edited by wildplace: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.