How to use getche () with do-while in C?

1

I have the following variable:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

char op;

And I'm asking the user to enter a character:

printf("\nDeseja realizar novo teste (s/n) ?");
op = getche();

If the user type s the following code will appear:

    printf("\nDigite um número para o dividendo : \n");
    scanf("%d", &dividendo);
    printf("\nDigite um número para o divisor : \n");
    scanf("%d", &divisor);

And if the user types n , the program exits, but if you type any other character, it appears, the same message asking you to perform a new test.

Code:

do {

printf("\nDeseja realizar novo teste (s/n) ?");
op = getche();

}while(getche() != 's' || getche != 'n');

It continues to run do-while , even if I put the characters s or n , how can I make it work?

    
asked by anonymous 10.05.2017 / 23:01

2 answers

2

To read a character, just use scanf itself.

char ch;
scanf(" %c", &ch);
printf("%c", ch);

Note that no scanf has a space before %c . This is to indicate that the function ignores any additional blanks that come from the keyboard and only reads the character. And avoid using getche , I think this function is not C's default.

Edit:

char op;
while (1) {

    printf("\nDeseja realizar novo teste (s/n) ?");
    op = getche();

    if (op == 's' || op == 'n') {
        printf("\n\nVc escolheu '%c'", op);
        break;
    }
}
    
10.05.2017 / 23:24
1

I think the problem lies in the fact that you are using the function in the condition, when in fact you would have to use the variable in the do-while condition. Try this way and see what happens:

do {

printf("\nDeseja realizar novo teste (s/n) ?");
op = getche();

}while(op != 's' || op != 'n');
    
10.05.2017 / 23:31