0
votes

I'm trying to scanf an integer to see if it's legal in my program. However, if I input a number followed by a char it still treats it as legal number (my guess is that it only refers to the integer while saving the char in the buffer). Assume I can only use scanf and not something else (since that's what we've leraned). Also, if I input only a char it automatically casts it to an integer. This is what I have tried so far, with the help of what I saw here -

 int number_of_numbers;
 char number='\n';
 printf("Enter size of input:");
 if (scanf("%d%c",&number_of_numbers, &number)>=1 && number!='\n')
    {
        printf("Invalid size");
        return 0;
    }

How can I identify when I scanf only an integer or an integer followed by a char or just a char? Thanks!

1
get input with fgets(), parse with strtoul() or similar and/or isalpha() or similar.pmg

1 Answers

0
votes

If you enter "only a character" it does not "automatically cast it to an integer". It does not accept any input at all, as shown by scanf returning 0, but that situation escapes your test.

But the answer to your question is: with difficulty when using scanf.

Here is a way to do it getting the input with fgets. It will tolerate any amount of whitespace before or after the number, but not any letters.

The reason for the space before %c is to instruct it to filter any leading whitespace. This is automatic anyway for %d, but not for %c. Then if there are no readable characters, nothing will be read into extra. If there is at least one character (apart from whitespace) then the sscanf conversion count will be incorrect.

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

int main(void)
{
    int number_of_numbers = 0;
    while(number_of_numbers >= 0) {
        bool success = false;
        char str[100];
        if(fgets(str, sizeof str, stdin) != NULL) {
            char extra;
            if(sscanf(str, "%d %c", &number_of_numbers, &extra) == 1) {
                success = true;
            }
        }
        if(success) {
            printf("Success: %d\n\n", number_of_numbers);
        } else {
            printf("Invalid size\n\n");
        }
    }
    return 0;
}

Program session:

123
Success: 123

123a
Invalid size

123 a
Invalid size

123 9
Invalid size

a
Invalid size

-1
Success: -1

The reasons for using fgets are

  • it doesn't "stall" if there is invalid input: it has already been read.

  • if there is a mistake, the string can easily be dumped and another one requested.