To get exactly Y/N for yes or no, and not other than those :-
-------------------------------------------------------------
here you need shared library for "clrscr-getch.h" and "str-manip.h"
first for "gotoxy(......) & other functions and second for "trimstring(......)"
I have already posted for both libraries.
This gets only "Y" or "N", and not mare than that. Even does not display other than characters "Y" or "N". By default "Y" option is dispalyed. If user hit direct "Enter key", before yes or no, default yes ("Y") is returened.
Here most of the validations are handled.
#include <iostream>
#include <clrscr-getch/clrscr-getch.h>
#include <str-manip/str-manip.h>
using namespace std;
bool getYesNo(const int xcoord, const int ycoord, char *yn);
int main()
{
bool tf;
char yn;
CClrscrGetch *get = new CClrscrGetch;
get->clrscr();
cout << "Enter Y/N : ";
tf = getYesNo(13, 1, &yn);
cout << endl;
if(tf == true)
{
cout << "Y/N : " << yn;
}
else
{
cout << "Invalid ";
}
cout << endl;
delete get;
return 0;
}
bool getYesNo(const int xcoord, const int ycoord, char *yn)
{
string strin;
char key = 'Y';
bool tf = false;
CClrscrGetch *get = new CClrscrGetch;
strin.clear();
int i = 0;
while(1)
{
get->gotoxy(xcoord, ycoord);
if(key == 'Y' || key == 'y' || key == 'N' || key == 'n')
{
key = char(toupper(key));
cout << key;
strin = key;
}
get->gotoxy(xcoord + 2, ycoord);
key = get->getch();
strin += key;
tf = CString::trimString(&strin);
if(tf == false)
{
continue;
}
if(tf == true && strin.length() > 1 && int(key) != 10)
{
strin.pop_back();
continue;
}
if(int(key) == 10) // Enter key = 10
{
*yn = strin.at(0);
delete get;
return true;
}
else
{
continue;
}
}
}
/* O/P :-
Enter Y/N : Y
Y/N :Y
[rahul@kaljayi Release]$
Enter Y/N : N
Y/N :N
[rahul@kaljayi Release]$
*/