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

Asked

Viewed 2,428 times

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 types 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 type n, the program leaves, but if you type any other character, it appears, the same message asking you to perform new test.

Code :

do {

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

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

He keeps running the do-while, even if I put the characters s or n, how can I make it work ?

2 answers

2


To read a character, just use scanf even.

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

Note that in the scanf has a space %c. This serves to indicate that the function ignores all additional blank spaces coming from the keyboard and read only the character. And avoid using getche, I think this function is not standard C.

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;
    }
}
  • I prefer to use scanf too, but it’s a college exercise, and clearly asks to use getche, even if I don’t want to use it. And he’s just giving problems with the getche().

  • Try to use an infinite loop and check the character with if. Test here with Visual Studio 2015 and it worked. I updated the code.

  • Yes, it worked. Thank you very much.

1

I think the problem is 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 it this way and see what happens:

do {

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

}while(op != 's' || op != 'n');
  • It also did not work, he keeps asking 3 times the same thing, and not the correct output. He can’t catch the yes or no, or another character, and it’s an infinite loop.

  • 1

    @Mondial, did you import the conio library? If not, put it in the header of the script: #include <conio. h>

  • Yes, I imported the conio library.

  • You helped too, thank you very much.

Browser other questions tagged

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