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: ");			
scanf("%ld",&input);

Recommended Answers

All 6 Replies

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.

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: ");
    fflush(stdout);

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

im not allowed to do such complicated way~~

Then don't try to do complicated things. :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.