Thread: Loop doesn't work

  1. #1
    Registered User
    Join Date
    Nov 2009
    Posts
    19

    Loop doesn't work

    In f_create() when it asks wether the user wants to enter a new record or not... wether you enter Y or N it just continues adding new records, can someone tell me whats wrong?

    Code:
    #include <stdio.h> 
    #include <stdlib.h>
    
    typedef struct 
    {
    	char id[5];
    	char first_name[20];
    	char surname[20];
    	int mem_type[5];
    	int expiry[5];
    } DATABASE;
    
    int f_menu ();
    void f_create();
    void f_append();
    void f_display();
    DATABASE f_add();
    
    void main()
    {
    	
    	int menu = 0;
    
    	menu = f_menu ();
    
    	do
    	{
    
    	switch (menu)
    	{
    	case 1 :
    		f_create ();
    		break;
    	case 2 :
    		f_display ();
    		break;
    	case 3 :
    		printf("Exiting Program\n\n");
    		break;
    	}
    } while (menu != 3);
    
    }
    
    int f_menu ()
    {
    	int menu = 0;
    
    	printf("\n\nLeisure Center Menu\n");
    	printf("  1. Add Members\n  2. Display Members\n  3. Exit\n ");
    	printf("\nEnter choice: ");
    
    	do
    	{
    		scanf("%d", &menu);
    		fflush(stdin);
    
    		if((menu < 1 ) || (menu > menu))
    		{
    			printf("Invalid choice. Try again: ");
    		}
    
    	} while ((menu < 1 ) || (menu > menu));
    
    	return (menu);
    }
    
    void f_create()
    {
    	  FILE *fp;
      DATABASE members;
      char reply;
    
      /* Open file to write to it */
      if ((fp = fopen ( "members", "wb" )) == NULL )
      {
        printf ( "Cannot open file\n" );
        return;
      }
    
      /* Loop while there are more students */
      do
      {
        /* Enter student details */
        members = f_add ();
    
        fwrite ( &members, sizeof(DATABASE ), 1, fp );
    
    	/* Choose another student or not */
        do
        {
          printf ( "Another record? > " );
    
    	  scanf ( "%c", &reply );
          fflush ( stdin );
          reply = toupper( reply );
        }
        while (( reply != 'Y' ) && ( reply != 'N' ));
    
      } /* End of loop for more students */
      while (( reply == 'Y' ));
    
      fclose (fp);
    }
    
    DATABASE f_add ()
    {
    	DATABASE members;
    
    	printf("Enter member ID : ");
    	gets(members.id);
    
    	printf("Enter first name : ");
    	gets(members.first_name);
    
    	printf("Enter surname : ");
    	gets(members.surname);
    
    	printf("Enter membership type : ");
    	scanf(members.mem_type);
    	fflush(stdin);
    
    	printf("Enter memership expiry month (1-12) : ");
    	scanf(members.expiry);
    	fflush(stdin);
    
    	/* Return structure containing student details */
    	return members;
    
    }
    
    void f_display ()
    {
      FILE *fp;
      DATABASE members;
    
      /* Open file to read from it */
      if ((fp = fopen ( "members", "rb" )) == NULL )
      {
        printf ( "Cannot open file\n" );
        return;
      }
    
      /* Read first record */
      fread ( &members, sizeof( DATABASE ), 1, fp );
    
      /* Loop while there are records in the file */
      while (!(feof (fp)))
      {
        /* Display previous record */
        printf ( "%s   %3d\n", members.id, members.first_name, members.surname, members.mem_type, members.expiry);
    	/* Read next record */
        fread ( &members, sizeof( DATABASE ), 1, fp );
      }
    
      fclose (fp);
    }
    
    void append()
    {
    
    }

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    You need to eat the NEWLINE character. Also, see the FAQ for scanf() and also fflush(stdin).
    Mainframe assembler programmer by trade. C coder when I can.

  3. #3
    Registered User
    Join Date
    Nov 2009
    Posts
    19
    Um... what?

    And yeh, People keep telling me about the scanf and gets and what not.. but its what I'm taught on my course, why learn what isn't gonna get me marks...

    but the loop problem?

  4. #4
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Quote Originally Posted by renvaar View Post
    ... why learn what isn't gonna get me marks...
    Remind me to never hire you.

    See this link:
    Cprogramming.com FAQ > Flush the input buffer

    Read it, and then at the bottom, click the link to see why fflush(stdin) is bad.
    Mainframe assembler programmer by trade. C coder when I can.

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by renvaar View Post
    Um... what?

    And yeh, People keep telling me about the scanf and gets and what not.. but its what I'm taught on my course, why learn what isn't gonna get me marks...

    but the loop problem?
    Because those things work, and they do nice things for your program.

    You need to pull the newline off of the keyboard buffer (if it's there), before you scanf() any char.

    getchar() will pull out one char from the keyboard buffer. Almost always, it's a newline char that needs to be pulled out.

  6. #6
    Registered User
    Join Date
    Nov 2009
    Posts
    19
    I have no idea what you are saying, and now I have another problem with my validation I added for this part...

    Code:
    printf("Enter memership expiry month (1-12) : ");
    	do
    	{
    		scanf(members.expiry);
    		fflush(stdin);
    
    		if ((members.expiry < 1) || (members.expiry > 12))
    		{
    			printf("Number between 1 and 12 corresponding to the month must be entered");
    		}
    	}while ((members.expiry) < 1 || (members.expiry > 12));
    I hate C... Never had these problems in VB...

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > why learn what isn't gonna get me marks
    Because it might help you keep your job in future.

    That is, assuming you have aspirations of C programming past the exam - do you?

    > I hate C
    It also helps to inform you that your teacher doesn't actually know that much about C at all. You might want to consider that when they say "x is true" when in fact everyone else knows better.
    You're being taught by someone who doesn't know C at all well, that's part of the problem.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Visual Basic was designed to be easy to learn, yet capable Note the word "Basic". C was designed to ROCK YOUR WORLD, and to be used by, professional programmers.

    You're having problems because your teacher has lead you into the deeper end of the pool, before making sure that you can swim well enough.

    If you don't know how to use scanf(), then you shouldn't be asked to use it. You can make up your own simple input function for C, that will do just what you want - but that is NOT scanf().

    Scanf() is fussy, quits unexpectedly, takes newlines as char entries, and has a boat load of options that are close to hieroglyphics from ancient Egypt for readability.

    You should NOT be using scanf(), and your teacher should KNOW that you should not be using scanf(). He or she, is just being lazy.

    Consider that one of the first functions that K&R have you work on in their book, is a better (more friendly and reliable), input function. They use that improved input function (getline), throughout their book "The C Programming Language".

    May not impress you unless you know that Brian Kernighan & Dennis Richie wrote C in the first place.


    scanf() is not the friendly little 4 letter input function that it appears.

  9. #9
    Registered User
    Join Date
    Nov 2009
    Posts
    19
    This is all great and very interesting, but nobody is helping me with my actual problems... My teacher sucks, I agree... but I still need to pass the course...

  10. #10
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Well, I tried, but you chucked my code out, replaced it with what you had before (more or less). I'm reluctant to help any more, because you don't seem like you want to listen.

    I'm not talking about the theory stuff - that's important, but can wait. (although fflush(stdin) will not work in WindowsXP reliably, even with good old Turbo C)

    Usually, I'd use some pointers, but I don't see any in your program, yet. Have you had pointers yet, at all?

    If not, is a global array of structs, OK? Somehow, someway, the functions have to be able to modify the student's data.

  11. #11
    Registered User
    Join Date
    Nov 2009
    Posts
    19
    What code have I chucked out? The only code posted is by me, and I haven't replaced anything... only added some validation in a totally seperate part (which I got working now). All I'm asking for is help on why the loop asking if the user wants to enter another record isn't working....

    Is it that hard to say "the loop doesnt work because this should be this bla bla"?

  12. #12
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Two things:

    1) You have a short memory:
    Can't fix errors

    2) You can't add more members because you only have room for ONE member. You need to make an array of those structs.

    Usually, you define the struct above main(), and then initialize the array of structs, in main(). After that, you pass the array to all your other functions that need to modify the contents.

    "bla bla", huh? Does have a certain ring to it, I guess.
    Last edited by Adak; 01-15-2010 at 04:44 AM.

  13. #13
    Registered User
    Join Date
    Dec 2009
    Posts
    2
    Use function flushall(); before each gets() and scanf();

  14. #14
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by pointer_to_HELP View Post
    Use function flushall(); before each gets() and scanf();
    WRONG!

    First, flushall() is not a standard C function.

    Second, if you intend is to flush the input buffer (stdin), NEVER DO THAT because it is undefined, altho it may seem to work, sometimes.

    If you are having problems with the input buffer and functions like scanf(), see this:
    STDIN pitfalls
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  15. #15
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > Use function flushall(); before each gets() and scanf();
    flushall() is a non-standard function, and using gets() for ANYTHING is brain-damaged. There is NO way to make gets() safe - see the FAQ.

    Using fgets() consistently would solve those issues.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. need help with a loop
    By Darkw1sh in forum C Programming
    Replies: 19
    Last Post: 09-13-2009, 09:46 PM
  2. funny-looking while loop
    By Aisthesis in forum C++ Programming
    Replies: 3
    Last Post: 08-30-2009, 11:54 PM
  3. loop the loop - feeling foolish
    By estos in forum C Programming
    Replies: 2
    Last Post: 04-07-2007, 02:45 AM
  4. Replies: 1
    Last Post: 10-27-2006, 01:21 PM
  5. fopen();
    By GanglyLamb in forum C Programming
    Replies: 8
    Last Post: 11-03-2002, 12:39 PM