Prevent people from type anything beside y or n in cin>>blablabla

To make it short. how do i prevent people from "typing" any key beside the one i chose (this case it's "y" and "n") when doing cin input.

1
2
3
4
5
6
7
8
9
10
11
 int startgame()
{
    cout << "Welcome..."<<endl;
    cout <<"Type in your name: ";
    cin >> pname;
    cout << "It's " << pname << " right?" <<endl;
    cout << "Yes[y]/No[n]";
    cin >> answer;
    if(answer=="n"){system("cls");startgame();};
    if(answer=="y"){bootgame();};
}
Try to remember this truc when you deal with one charcter use getch() function it efficent like hello!!

1
2
3
4
5
6
7
8
9
10
11
int startgame(void)
{
    cout << "Welcome..." << endl;
    cout << "Type in your name: ";
    cin >> pname;
    cout << "It's " << pname << " right?" << endl;
    cout << "Yes[y]/No[n]";
    answer = getch();
    if(answer=='n'){system("cls");startgame();};
    if(answer=='y'){bootgame();};
}


dont forget to include <conio.h>

hope that helps
Last edited on
You can not. People never do as told.

What you can do is to ask again (in a loop) until the input is valid.

You actually appear to have a loop already, but it is recursive rather than iterative. Not a nice design.

While at it, check that 0 < pname.size(). I bet "" is not a nice name.

Moreover, you don't want to use global variables. Really.
If you want to ignore any other characters typed by the user and you do not want them to be displayed (echoed) on the screen, you will probably have to use a curses library.

http://www.tldp.org/HOWTO/NCURSES-Programming-HOWTO/init.html#ECHONOECHO
@abhishekm71

You Said:
you will probably have to use a curses library


Not true, you can use conio.h.
grumble grumble

While it is true that curses is not the only solution... conio.h is ancient and not officially apart of the C standard or the C++ standard. conio.h was used in old MS-DOS programs to make textual user interfaces. conio.h differs from compiler to compiler and OS to OS. Unless you are studying Turbo C or writing some old DOS application, please do not use conio.h.

curses is a far better solution in my opinion. curses is available on all platforms as opposed to conio.h which is not available on all platforms.

you will probably have to use a curses library
probably
makes the statement probably true.

Not true, you can use conio.h

This statement is false if the person reading it does not have conio.h on their platform.

Alright I am done grumbling.
Yes, but he is only a beginner. I would not recommend that unless you really want to change how you code.

So far, the easiest thing for me was PDcurses, but I might as well just get wxWidgets and start writing GUI...
Topic archived. No new replies allowed.