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.

Recommended Answers

All 6 Replies

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'));

Or fairly portable libraries like ncurses.

curses on windows is extremely iffy

>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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.