Program to get options (Y/y) for yes or ( N/n) for no. Neither will be accepted other than those.
#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
using std::endl;
char charExtract(string str)
{
string::iterator istr;
char ch;
istr = str.begin();
ch = *istr;
if(str.length() == 1)
return ch;
else
return 0;
}
bool yesno()
{
string str;
char ch;
int i;
while(1)
{
cout << "Enter y(yes) or n(no) : ";
getline(cin, str);
if(str.length() == 0 )
continue;
else
{
ch = charExtract(str);
if(ch == 'Y' || ch == 'y')
{
return true;
}
else if(ch == 'N' || ch == 'n')
{
return false;
}
else
{
cout << "\nEnter only Y(yes) or N(No)" << endl;
}
}
}
}
int main()
{
bool yn = yesno();
if(yn == true)
{
cout << "true" << endl;
}
else if( yn == false)
{
cout << "false" << endl;
}
return 0;
}
/*
output :-
-------------
[rahul@C-Client Release]$ ./yes-no
Enter y(yes) or n(no) : YES
Enter only Y(yes) or N(No)
Enter y(yes) or n(no) : NO
Enter only Y(yes) or N(No)
Enter y(yes) or n(no) : Nu
Enter only Y(yes) or N(No)
Enter y(yes) or n(no) : 123
Enter only Y(yes) or N(No)
Enter y(yes) or n(no) : 1
Enter only Y(yes) or N(No)
Enter y(yes) or n(no) : 0
Enter only Y(yes) or N(No)
Enter y(yes) or n(no) : Y
true
[rahul@C-Client Release]$ ./yes-no
Enter y(yes) or n(no) : y
true
[rahul@C-Client Release]$ ./yes-no
Enter y(yes) or n(no) : N
false
[rahul@C-Client Release]$ ./yes-no
Enter y(yes) or n(no) : n
false
[rahul@C-Client Release]$
*/
No comments:
Post a Comment