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;
}
elseif (ch == 'N')
cout << "Sds";
}
#include <iostream>
#include <string>
#include <conio.h>
usingnamespace std;
int main()
{
char ch='A';
int point=1234;
while(ch != 'Y' && ch != 'N')
{
ch=toupper(getch());
if ( ch == 'Y') point = 0;
elseif (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'.
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?
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;
}
}