Little problem with getch()

char ch = toupper(getch());
while(ch != 'Y' && ch != 'N') {
if ( ch == 'Y') {
point = 0; }
else if (ch == 'N')
cout << "Sds"; }

The firs time enter "Y/N" it works.
but If i enter any key except 'Y/N' it wont let me enter 'Y/N' again.

Thank You
Note that I haven't modified your code, just reformatted and added a comment saying why it doesn't work. (What I mean is: Don't spend your time trying to see what's different between your code and mine.)

1
2
3
4
5
6
7
8
9
10
11
char ch = toupper(getch());

// You only enter the while loop if you have a ch that is *not* 'Y' and *not* 'N'.
// Furthermore, there is nothing inside the loop that changes ch to break the loop.
while(ch != 'Y' && ch != 'N') {
  if ( ch == 'Y') {
    point = 0;
  }
  else if (ch == 'N')
    cout << "Sds";
}


Let us know if this helps (or doesn't).
If you want to make a loop that forces the user to enter either 'Y' or 'N' as a value for ch then this might be what you're looking for:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string> 
#include <conio.h>
using namespace std;

int main()
{

    char ch='A';
    int point=1234;

    while(ch != 'Y' && ch != 'N')
    {
         ch=toupper(getch());
      
         if ( ch == 'Y') point = 0;
         else if (ch == 'N') cout << "Sds" << endl;
    }
    
    cout << "point: " << point << endl;
    
    cout << "hit any key to quit..." << endl;
    getch();
    return 0;	
}


Note that the character input command ("ch=toupper(getch());") is inside the loop, and ch is initialized to something that is neither 'Y' nor 'N' so that the loop is guaranteed to run at least once. The loop continues until you enter 'Y' or 'N'.
Last edited on
Yes it does.
Why are you even using getch()? It's non standard.
i thought use getch() is easier because i only want Y/N answer and i dont need to write a statement to tell the user, he/she entered the wrong answer.
Also this my first semester learning c++ so dont know much about other methods.

What is the best and simple way to get Y/N answer?
Use cin.get().
But what if i enter too many 'Y'. it will keep display SDR.
void option() {
char ch;
while(ch != 'Y' && ch != 'N') {
ch = toupper(cin.get());
if ( ch == 'Y') {
point = 0;
cout << "SDR"<< endl;
}
}
Topic archived. No new replies allowed.