How to read only integer numbers in scanf?

1

For example, in the code:

int main() {
    int x;

    scanf("%d", &x);          

 printf("%d", x);
}

If I type "A", it automatically converts to integer or just closes the program (the two have already happened to me). there, in the case, it prints 39. how do I get the program to accept integers only?

    
asked by anonymous 15.10.2018 / 21:31

3 answers

5

You need to put #include <stdio.h> into scanf and printf. Also, you need to initialize the variable "x", otherwise it will have "garbage". If you type "A" and enter, the "A" you typed is not placed in the "x", what printf shows is the "junk" content of "x" that you did not initialize.

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

#include <stdio.h>

int main()
{
  int x = -1;
  scanf("%d", &x);
  printf("%d", x);
}
    
15.10.2018 / 21:40
3

There are basically two forms:

15.10.2018 / 21:44
1

Putting what you have already got into the other code responses, you can test the return of scanf until you give 1 signaling that you were able to read 1 integer 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 little annoying to have to write this all down to make sure it reads 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 somewhat harder possibility would be to always read everything as string and interpret the data you want from the string read. In case an integer could try to interpret an integer at the expense of strtol and check if it was unsuccessful ask for another one again.

    
16.10.2018 / 00:16