Force user to enter integer numbers in an array

Asked

Viewed 66 times

0

Person, what would be the best structure to force the user to enter positive integers within an array (array), the code fragment I copied here is inside a function, it works ok when first executed, however if I call it again at another time, the system does not consider the entered value, but rather that of the position of i. for example

int consumidor[50];
int i = 0, continuar = 1;

while (continuar = 1){

while (consumidor[i] < 1) 

{

printf("Insira o código do consumidor a ser cadastrado: ");

scanf_s("%d", &consumidor[i]);

if (consumidor[i] < 1) {

printf("Digite um código superior a '0'.\n");
            }


i++;

printf("Deseja inserir um novo consumidor? Digite '1' para sim ou tecle qualquer outra tecla para sair. ");



scanf_s("%d", &continuar);

}

1 answer

0


Although you say it’s correct you’ve noticed that here: while (continuar = 1){ you are assigning 1 to the variable continuar and not checking if its value is 1?

int consumidor[50];
int i = 0, continuar = 1;
while (continuar == 1 && i < 50) {
    do {
        printf("Insira o código do consumidor a ser cadastrado: ");
        scanf_s("%d", &consumidor[i]);
        if (consumidor[i] < 1) {
            printf("O código precisa ser superior a '0'.\n");
        }
    } while (consumidor[i] < 1);
    i++;
    printf("Deseja inserir um novo consumidor? Digite '1' para sim ou '2' para sair. ");
    scanf_s("%d", &continuar);
}

Browser other questions tagged

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