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(......)"
for this you must have added library "clrscr-getch.so".
This gets only "Y" or "N", and not mare than that. Even does not displays other than character "Y" or "N. By default that char will be displayed
which is passed as argument in "char *yn", here in call of function if you pass 'Y', then by default option is displayed as Y, but if you pass
'N' by default option is displayed is 'N'. And here If user hit direct "Enter key", before yes or no, default passed char will be returened.
if you pass other than 'Y' or 'N', then also 'Y' will be displayed.
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 = 'L'; // or any other character
// char yn = 'N';
char yn = 'Y';
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;
string::iterator istr;
char key;
bool tf = false;
CClrscrGetch *get = new CClrscrGetch;
strin.clear();
int i = 0;
if(*yn != 'Y' && *yn != 'y' && *yn != 'N' && *yn != 'n')
{
key = 'Y';
}
else
{
key = *yn;
}
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);
if(*yn == 'Y' || *yn == 'y' || *yn == 'N' || *yn == 'n')
{
return true;
}
else
{
continue;
}
}
else
{
continue;
}
}
}
/*
O/P :-
Enter Y/N : N
Y/N : N
[rahul@kaljayi Release]$
Enter Y/N : Y
Y/N : Y
[rahul@kaljayi Release]$
*/