472,952 Members | 2,197 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,952 software developers and data experts.

Menu looping

sk
Hi everyone, I'm kind of new to C programming, so I thought that a
newsgroup would be the best place to ask a question about this.

I'm trying to write a small program that displays a menu and has the
user input a value(int). I'm only using getchar and printf to make
things simple.

I have the menu printing part down pretty well, but I'm getting an error
where the entire menu will print n+1 number of times when you input a
value with n-digits. I asked around a little, and some others said that
it was because getchar is buffered, and will just print for every char
that is passed. I'm stuck on how to make it so that the menu will only
print once, then ask the use for input.

This is how it is set up right now:

prints menu
getchar
while (getchar variable is not EOF)
{
prints menu
(conditionals for menu...)
getchar
}

Can anyone give me any ideas on how to fix this? Sorry if this is a
stupid question. Thanks in advance!
Feb 28 '06 #1
10 2947
"sk" <sk******@purdue.edu> wrote in message
news:7a5Nf.794387$x96.655350@attbi_s72...
Hi everyone, I'm kind of new to C programming, so I thought that a
newsgroup would be the best place to ask a question about this.

I'm trying to write a small program that displays a menu and has the
user input a value(int). I'm only using getchar and printf to make
things simple.

I have the menu printing part down pretty well, but I'm getting an error
where the entire menu will print n+1 number of times when you input a
value with n-digits. I asked around a little, and some others said that
it was because getchar is buffered, and will just print for every char
that is passed. I'm stuck on how to make it so that the menu will only
print once, then ask the use for input.

This is how it is set up right now:

prints menu
getchar
while (getchar variable is not EOF)
{
prints menu
(conditionals for menu...)
getchar
}

Can anyone give me any ideas on how to fix this? Sorry if this is a
stupid question. Thanks in advance!


You may consider using a do-while loop since it may suit your needs better.
As far as the implementation is concerned, you can try reading the first
character of the user input and discard the rest of the input line. The end
of a line is signaled with getchar() returning '\n'. In any case you should
always look out for EOF as you already have. Do not forget to store the
getchar() return in an int. Feel free to post your code here in your
attempts towards the desired behaviour.
Mar 1 '06 #2
sk
stathis gotsis wrote:
"sk" <sk******@purdue.edu> wrote in message
news:7a5Nf.794387$x96.655350@attbi_s72...
Hi everyone, I'm kind of new to C programming, so I thought that a
newsgroup would be the best place to ask a question about this.

I'm trying to write a small program that displays a menu and has the
user input a value(int). I'm only using getchar and printf to make
things simple.

I have the menu printing part down pretty well, but I'm getting an error
where the entire menu will print n+1 number of times when you input a
value with n-digits. I asked around a little, and some others said that
it was because getchar is buffered, and will just print for every char
that is passed. I'm stuck on how to make it so that the menu will only
print once, then ask the use for input.

This is how it is set up right now:

prints menu
getchar
while (getchar variable is not EOF)
{
prints menu
(conditionals for menu...)
getchar
}

Can anyone give me any ideas on how to fix this? Sorry if this is a
stupid question. Thanks in advance!


You may consider using a do-while loop since it may suit your needs better.
As far as the implementation is concerned, you can try reading the first
character of the user input and discard the rest of the input line. The end
of a line is signaled with getchar() returning '\n'. In any case you should
always look out for EOF as you already have. Do not forget to store the
getchar() return in an int. Feel free to post your code here in your
attempts towards the desired behaviour.


Thank you for your quick reply!

I tried to use the do while, but it's still printing n+1 times...
I'm trying to make something like a stripped down calculator where it
will print a menu, ask for input, print out data, then loops over again.
It will stop when the user pushes ctrl-d or inputs a '0';

Just another quick question. What is the difference between storing the
getchar() return to an int instead of a char?
Mar 1 '06 #3
sk wrote:

You may consider using a do-while loop since it may suit your needs
better.
As far as the implementation is concerned, you can try reading the first
character of the user input and discard the rest of the input line.
The end
of a line is signaled with getchar() returning '\n'. In any case you
should
always look out for EOF as you already have. Do not forget to store the
getchar() return in an int. Feel free to post your code here in your
attempts towards the desired behaviour.


Thank you for your quick reply!

I tried to use the do while, but it's still printing n+1 times...
I'm trying to make something like a stripped down calculator where it
will print a menu, ask for input, print out data, then loops over again.
It will stop when the user pushes ctrl-d or inputs a '0';

Just another quick question. What is the difference between storing the
getchar() return to an int instead of a char?


Did you remove the first prints menu before the loop?

--
Ian Collins.
Mar 1 '06 #4
sk
Ian Collins wrote:
sk wrote:

You may consider using a do-while loop since it may suit your needs
better.
As far as the implementation is concerned, you can try reading the first
character of the user input and discard the rest of the input line.
The end
of a line is signaled with getchar() returning '\n'. In any case you
should
always look out for EOF as you already have. Do not forget to store the
getchar() return in an int. Feel free to post your code here in your
attempts towards the desired behaviour.


Thank you for your quick reply!

I tried to use the do while, but it's still printing n+1 times...
I'm trying to make something like a stripped down calculator where it
will print a menu, ask for input, print out data, then loops over
again. It will stop when the user pushes ctrl-d or inputs a '0';

Just another quick question. What is the difference between storing
the getchar() return to an int instead of a char?


Did you remove the first prints menu before the loop?


Yes, I have. I've also tried many combinations of while loops/print
statements, and it still prints too many times. :(
Mar 1 '06 #5
sk wrote:
Hi everyone, I'm kind of new to C programming, so I thought that a
newsgroup would be the best place to ask a question about this.

I'm trying to write a small program that displays a menu and has the
user input a value(int). I'm only using getchar and printf to make
things simple.

I have the menu printing part down pretty well, but I'm getting an error
where the entire menu will print n+1 number of times when you input a
value with n-digits. I asked around a little, and some others said that
it was because getchar is buffered, and will just print for every char
that is passed. I'm stuck on how to make it so that the menu will only
print once, then ask the use for input.

This is how it is set up right now:

prints menu
getchar
while (getchar variable is not EOF) getchar takes char by char buffering chars ...
and you want a multiple char entry...
Don't you want to use fgets, sscanf ? then test on strlen (buf) == 0 to exit {
prints menu
(conditionals for menu...)
getchar
}

Can anyone give me any ideas on how to fix this? Sorry if this is a
stupid question. Thanks in advance!

Mar 1 '06 #6

"sk" <sk******@purdue.edu> schrieb im Newsbeitrag
news:C47Nf.794542$x96.597967@attbi_s72...

read this part again...
As far as the implementation is concerned, you can try reading the
first
character of the user input and discard the rest of the input line. The
end
of a line is signaled with getchar() returning '\n'. In any case you
should
always look out for EOF as you already have. Do not forget to store the
getchar() return in an int. Feel free to post your code here in your
attempts towards the desired behaviour.
getchar() will buffer your input until you press enter.
then the next calls will return each character, including a '\n' for enter.

some loop {
menu();

c = getchar();

/* do something */

/* forget the rest of the line */
while (c != '\n' && c != EOF)
c = getchar();
}

Just another quick question. What is the difference between storing the
getchar() return to an int instead of a char?

EOF (end of file/no more input) is no regular character and if you put the
result in a char... then there will be a character and a eof that you cant
distinguish.

Did you remove the first prints menu before the loop?


Yes, I have. I've also tried many combinations of while loops/print
statements, and it still prints too many times. :(


or look what xavier wrote...

f~
Mar 1 '06 #7
sk wrote:
What is the difference between storing the
getchar() return to an int instead of a char?


EOF is not a char.

if ((char)getchar() == EOF) /* is *never* true */

--
If you're posting through Google read <http://cfaj.freeshell.org/google>
Mar 1 '06 #8
Pedro Graca <he****@dodgeit.com> writes:
sk wrote:
What is the difference between storing the
getchar() return to an int instead of a char?


EOF is not a char.

if ((char)getchar() == EOF) /* is *never* true */


Not quite. EOF is guaranteed to have a negative value of type int
(it's typically -1). If plain char happens to be signed, the
condition can be true *either* if getchar() returns EOF (and EOF is
within the range of signed char) *or* if getchar() returns a valid
character whose value happens matches the value of EOF. On many
systems, the latter will occur if the input character is character
255, which is a y with an umlaut ('') in Latin-1 (a common extension
of ASCII).

getchar() returns either the value EOF, or the next character from
stdin converted to unsigned char and then converted to int. Storing
the value in an int rather than a char lets you distinguish between
character 255 and -1.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 1 '06 #9
sk wrote:
.... snip ...
I have the menu printing part down pretty well, but I'm getting an
error where the entire menu will print n+1 number of times when
you input a value with n-digits. I asked around a little, and some
others said that it was because getchar is buffered, and will just
print for every char that is passed. I'm stuck on how to make it
so that the menu will only print once, then ask the use for input.

This is how it is set up right now:
.... snip non-compilable code ...
Can anyone give me any ideas on how to fix this? Sorry if this is
a stupid question. Thanks in advance!


Show us compilable code, and tell us what problems you have with
it. At any rate, the following is an expansion of something I
explained in another thread a few days ago. It compiles, but has
not been tested.

#include <stdio.h>
#include <ctype.h>
#include <string.h>

/* ------------------ */

int skipblanks(FILE *f)
{
int ch;

while (' ' == (ch = getc(f))) continue;
return ch;
} /* skipblanks */

/* ------------------ */

int flushln(FILE *f)
{
int ch;

while (('\n' != (ch = getc(f))) && (EOF != ch)) continue;
return ch;
} /* flushln */

/* ------------------ */

/* Print optional menu and get a single char response. Repeat
as needed until the response is in the acceptable string.
If the first char in acceptable is uppercase, use that as
a default response when a blank line is entered.
Returns response initial char or EOF.
*/
int menuget(const char *prompt, /* whatever prompt is needed */
const char *acceptable) /* list of acceptable ans */
{
int ch;

do {
if (prompt) {
printf("%s", prompt); fflush(stdout);
}
/* Now get a reply */
ch = skipblanks(stdin); /* get first non-blank char */
if ('\n' != ch) flushln(stdin); /* set up to try again */
else if (isupper(acceptable[0])
ch = acceptable[0]; /* 1st is default entry */
} while (!strchr(acceptable, ch) && (EOF != ch));
return ch;
} /* menuget (untested) */

You could call this with something like:

ch = menuget("Enter your desire\n"
" A or a for all\n"
" b for botheration\n"
" x for quit : ",
"Aabx";

Notice the merged strings for the prompt.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Also see <http://www.safalra.com/special/googlegroupsreply/>
Mar 1 '06 #10
sk wrote:

I have the menu printing part down pretty well, but I'm getting an error
where the entire menu will print n+1 number of times when you input a
value with n-digits.

prints menu
getchar
while (getchar variable is not EOF)
{
prints menu
(conditionals for menu...)
getchar
}


getchar() gets a char. If you enter 10 chars then it your
loop will obviously execute 10 times, once for each char.

It sounds like what you want to do is discard all input up
until the '\n' (enter key), each time you have successfully
read a char. (Another option would be to use a platform-
specific function that returns immediately upon keypress).

Also, if you make the getchar() part of the loop condition
then you don't have to duplicate it.

For example:

int ch;
while ( EOF != (ch = getchar()) )
{
/* consume extra input */
if ( ch != '\n' )
while ( getchar() != '\n' );

do_stuff();
}

Mar 2 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Angelos | last post by:
Hello there... I am trying for a long time now, to find a way of creating a dynamic drop down menu. I have the CSS part ready and working and also I have the first level of the menu working. the...
1
by: paakwesi | last post by:
I'm looking to modify the javascript behavior on http://research.yale.edu/%7Ekamusi/exercises/learners/index.php to do two things: Initial State: Both menus are populated with all their entries...
6
by: daniel.sumanth | last post by:
Hello, Have customized the menu options in Access 2000 in a computer. However, it seems that the customizations apply only when I'm logged in and not to other users. Is there any way to use the...
3
by: Sameh Ahmed | last post by:
Hello there Need to create a context menu in runtime, everything is ok except that I need to check if a menuitem called "whatever" already exists in the context menu. Below is the code I use that...
5
by: Martin | last post by:
I have a menu, a rather big one. It contains about 150 items. Normally this would mean that I'd have about 150 event handlers: Private Sub Menu1_Click(ByVal sender As System.Object, ByVal e As...
1
by: iwdu15 | last post by:
hi, i added an item to the system menu for every application (looping through each process and using the MainWindowHandle to get the handle, the using the GetSystemMenu and AppendMenu APIs to add a...
20
by: Ifoel | last post by:
Hi all, Sorry im beginer in vb. I want making programm looping character or number. Just say i have numbers from 100 to 10000. just sample: Private Sub Timer1_Timer() if check1.value= 1...
0
by: divya1949 | last post by:
Create a windows c# application which will Read a xml file and populate nodes in the treeview. 1 On selection of treenode display the child nodes of that node in listview control 2. ...
1
by: Franck | last post by:
I'm looking at a way to loop throught all menuitem object of a form, including sub menu. From the form it self sub items doesn't matter because i can access them directly without having to pass by...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.