Hey

I have this code:

void menu()
{
char opt
do
{
system ("cls");
printf ("1 - Option 1");
printf ("2 - Option 2");
printf ("3 - Option 3");
[B]scanf ("%c",&opt);[/B]
[B]}while ((opt!="1") && (opt!="2") && (opt!="3"));[/B]

The lines in bold are the ones Im not sure about.

What I want to do is a menu that displays, the cursor blinks, and I have to press a key (In this case 1, 2 or 3) and as soon as I press it, it enters the option (by using a case which I understand for now). If incorrect it simply displays the menu again. I just want to hit one key and not enter the option then have to hit the enter key.

Hi,
with "scanf ("%c",&opt);" you get char as an input. Scanf does not know how many Charactes your input is, so you need to press enter.

"}while ((opt!="1") && (opt!="2") && (opt!="3"));" is okay because it forces the input to be 1|2|3. For a menu in c it is okay.

>I just want to hit one key and not enter the option then have to hit the enter key.
There's no portable way to do this. You have to rely on a non-standard function like getch.

About scanf ("%c",&opt); -- See this information...

"}while ((opt!="1") && (opt!="2") && (opt!="3"));" is okay because it forces the input to be 1|2|3. For a menu in c it is okay.

No it's not. "1" is a string but opt is a character. Okay is }while ((opt!='1') && (opt!='2') && (opt!='3'));

>I just want to hit one key and not enter the option then have to hit the enter key.
There's no portable way to do this. You have to rely on a non-standard function like getch.

Fine by me :) Getch is "standard" in VS so It'll work in my case. Nonstandard functions (as long as its nothing really weird) are OK.

This article has been dead for over six months. Start a new discussion instead.