Error in my C Program

1

When I type 0 it does not report as the program should: "Incorrect entry. Enter an integer value".

#include <stdio.h>

void LimpaBuffer(void)
{  
    int valorLido; /* valorLido deve ser int */
    do {
        valorLido = getchar();
       } while((valorLido = '\n') && (valorLido !=EOF));
}
int main(void)
{
    int umInt, outroInt, nValoresLidos;
    printf("Digite um valor inteiro");
    nValoresLidos = scanf("%d", &umInt);
    while(nValoresLidos == 0) { //Nenhum inteiro for lido
        LimpaBuffer();
        printf("Entrada incorreta. Digite um valor inteiro");
        nValoresLidos = scanf("%d", &umInt);
    }
    printf("Digite outro valor inteiro");
    nValoresLidos = scanf("%d", &outroInt);
    while (nValoresLidos == 0) {
        LimpaBuffer();
        printf("Entrada incorreta. Digite um valor inteiro");
        nValoresLidos = scanf("%d", &outroInt);

    }
    printf("\n%d + %d = %d", umInt, outroInt, umInt + outroInt);
    return 0;
}
    
asked by anonymous 17.12.2014 / 14:19

2 answers

3

In loop while you are checking nValoresLidos , but scanf does not assign value to nValoresLidos , but outroInt .

Do this:

scanf("%d", &outroInt);
nValoresLidos = outroInt;
    
17.12.2014 / 14:29
5

This program is correct. What is wrong is the AP's way of thinking.

The while(nValoresLidos == 0) means:

While scanf does not read, in this case a %d gives read error!

For example if you type:

Digite um valor inteiro
0
Digite outro um valor inteiro
1

0 + 1 = 1

It's very correct.

In this case '0' is not a wrong form in input .

[Edit]

In addition, this line is missing a ! :

} while((valorLido = '\n') && (valorLido !=EOF));

should be:

} while((valorLido != '\n') && (valorLido !=EOF));

This will work properly.

    
17.12.2014 / 14:43