How to read only whole numbers in the scanf?

Asked

Viewed 1,572 times

1

For example, in the code:

int main() {
    int x;

    scanf("%d", &x);          

 printf("%d", x);
}

If I type "A", it automatically converts to whole or just closes the program (both happened to me). then, in this case, it prints 39. how do I make the program accept only whole numbers?

3 answers

4


You need to put the #include <stdio.h> for the scanf and the printf.
Also, you need to initialize the "x" variable, otherwise it will have "trash".
If you type "A" and enter, the "A" you entered is not placed in the "x", what the printf shows is the "trash" content of the "x" that you didn’t initialize.

In the example below, if you type "A" the "printf" will always show "-1".

#include <stdio.h>

int main()
{
  int x = -1;
  scanf("%d", &x);
  printf("%d", x);
}

4

1

By putting what you already got in the other code answers, you can test the return of scanf until 1 which signals that it has been able to read 1 entire successfully:

int x;
while (scanf("%d", &x) != 1){ //enquanto não ler 1 inteiro
    static char temp[256];
    fgets(temp, sizeof(temp), stdin); //limpa tudo o que ficou na entrada lendo como string
    printf("Digite um numero ");
}

Although it may seem a bit boring to have to write all this to make sure you read an integer, it’s something you can easily abstract in an auxiliary function:

int ler_inteiro(){
    int num;
    while (scanf("%d", &num) != 1){
        static char temp[256];
        fgets(temp, sizeof(temp), stdin);
        printf("Digite um numero ");
    }
    return num;
}

int main() {
    int x = ler_inteiro();
    int y = ler_inteiro();

    printf("%d %d", x, y);
}

See this example in Ideone

Another possibility a little more laborious would be to always read everything as a string and interpret the data you want the string to read. In case a whole could try to interpret a whole at the expense of strtol and check if you were unsuccessful to re-order another.

  • Good answer, I thought to write something like this but I got lazy. : ) In fgets to clean the input buffer it might be better to use BUFSIZ instead of 256. I don’t know why these courses insist on using scanf, only gives problems, and in my experience this is never used in programs "really".

  • @zentrunix Thanks for the comment. Yes it is best to use sizeof which is one less place to trade, which is what I usually do this time it didn’t even occur to me.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.