0

I have to make a program that reads an integer (N+) and then read a series of other integers (N+), but the program needs to check if the user has inputted chars mixed in the numbers the scanf() reads, in affirmative, the program will repeat the scanf(). So I decided to check the return value of scanf(). It works if I use only character input, but when I mixed it with integers, the program reads the integer and uses the maintained character on the buffer. How can I solve this?

#include <stdio.h>

int main() {
  int tamanho = 0, verificador = 0;

  do {
    printf("Digite um valor n>0: ");
    verificador = scanf("%d", &tamanho);
    getchar();
    if (verificador != 1) {
      printf("\nO programa aceita apenas valores inteiros\n");
      printf("Tente novamente\n");
    }
  } while (verificador != 1);

  int conjunto[tamanho];

  do {
    printf("Digite os numeros do conjunto de tamanho 'n': ");
    for (int i = 0; i < tamanho; i++) {
      verificador = scanf("%d", &conjunto[i]);
      if (verificador != 1) {
        printf("\nO programa aceita apenas números\n");
        printf("Tente novamente\n");
        getchar();
        break;
      }
    }
  } while (verificador != 1);

  printf("numero = %d\n", tamanho);

  for (int i = 0; i < tamanho; i++) {
    if (i <= tamanho - 2) {
      printf("%d, ", conjunto[i]);
    } else if (i == tamanho - 1) {
      printf("%d.\n", conjunto[i]);
    }
  }

  return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 4
    Short answer: You can't. If you want to read input with `scanf`, you will have to settle for poor error handling, with some error cases not easily handleable. If you want to handle all error cases, you will have to [use something other than `scanf`](https://stackoverflow.com/questions/58403537). See also [this recent question](https://stackoverflow.com/questions/73836358), and its comments and answers. Also [this other recent question](https://stackoverflow.com/questions/73840378). – Steve Summit Sep 28 '22 at 21:11
  • 1
    In [this answer of mine to another question](https://stackoverflow.com/a/73841194/12149471), I addressed the issue of `scanf` misbehaving if you enter for example `6abc` and also provided a solution. I believe that using my function `get_int_from_user` which I posted in that answer will solve all your problems. – Andreas Wenzel Sep 28 '22 at 21:23
  • Please note that your question would be of higher quality if you provided a [mre] of the problem. Most of your posted code is not necessary in order to demonstrate the problem. – Andreas Wenzel Sep 28 '22 at 21:34
  • @umhyliano, This is possible, yet needs clarification. When does input stop for reading 1 integer? The `'\n'`, end-of-file or what? How about "then read a series of other integers"? What is user only type an key? Providing samples of good input and samples of bad input would help. – chux - Reinstate Monica Sep 28 '22 at 22:14

0 Answers0