Thread: fgets question

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    58

    fgets question

    Hi all;


    If i have the following:
    Code:
    typedef struct {
    	char firstname[10];
    	char surname[10];
    	int age;
    }database;

    and i want to take in values for firstname and surname and age like this:
    Code:
    for(int i=0; i<5;i++)
    {
           fgets(ptr[i]->firstname, sizeof(ptr[i]->firstname), stdin);
           printf("\nEnter the surname");
           fgets(ptr[i]->surname, sizeof(ptr[i]->surname), stdin);
           printf("Enter the age");
            scanf("%d",&ptr[i]->age);
    }
    There is some code above missing, ie mallocs etc.

    The scanf causes the firstname to be skip on the next round of the loop.
    What can i use instead of scanf to solve the problem, i know its to with scanf not taking spaces, so firstname takes the space and thats why its blank


    Any ideas?

    Thanks

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    scanf() doesn't read the newline, so the fgets() reads the newline. Search this forum for "scanf buffer" and you'll find tons of hits.
    Mainframe assembler programmer by trade. C coder when I can.

  3. #3
    Registered User
    Join Date
    Aug 2009
    Posts
    58
    Didnt find much on it, could you post us a link?

  4. #4
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Didn't find much? I got 20 pages of hits for that argument.

    Entering Char problem
    Mainframe assembler programmer by trade. C coder when I can.

  5. #5
    Registered User
    Join Date
    Aug 2009
    Posts
    58
    So for my struct example i have an array for my int so i can use fgets on it?

  6. #6
    Registered User
    Join Date
    Aug 2009
    Posts
    58
    Its ok i solved it, ignore stupid comment by me above

    Thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fgets question
    By mattyg in forum C Programming
    Replies: 2
    Last Post: 12-01-2008, 04:25 AM
  2. Question on using fgets
    By gp364481 in forum C Programming
    Replies: 6
    Last Post: 10-17-2008, 10:23 AM
  3. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  4. fgets problem (i think)
    By GanglyLamb in forum C Programming
    Replies: 3
    Last Post: 03-19-2003, 11:19 AM
  5. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 09:22 PM