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;
}