Accessing Data within a struct! Need help please

This is a discussion on Accessing Data within a struct! Need help please within the C Programming forums, part of the General Programming Boards category; Code: #include <stdio.h> #include <string.h> #define MAX_NUM 53 //declare struct of type lotto struct lotto { char firstname [19]; char ...

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    244

    Accessing Data within a struct! Need help please

    Code:
    #include <stdio.h>
    #include <string.h>
    
    #define MAX_NUM 53
    
    //declare struct of type lotto
    struct lotto
    {
    char firstname [19];
    char lastname [19];
    int ticket_num[5];
    int winnings;
    };
    
    
    int main () 
    {
       struct lotto *info;
       int winning_nums [5], num_tickets, moneywon;
       int i, q, g, f, r, t, win3, win4, win5, win6;
       int matches=0;
       char filename[20];  
    
       FILE *ifp;
       
       //Prompt user for filename with lottery ticket info
       printf("Please enter the filename with the ticket information.\n");
       scanf("%s", &filename);
       ifp = fopen(filename, "r");
    
       //Scan number of lottery tickets on file
       fscanf(ifp, "%d", &num_tickets);
       
       //Allocate dynamic memory
       info=malloc(num_tickets*sizeof(struct lotto));
       
       //Scan first and last name for lottery info file
       for(t=0; t<num_tickets; t++){
          fscanf(ifp, "%s %s", &info[t].lastname, &info[t].firstname);
    	  }
    	   
        printf("%s\n", info[0].firstname, info[0].lastname);  // HERE IS WHERE I AM HAVING TROUBLE. 
    IT SCANS FIRST AND LAST  NAME FROM THE .TXT doc GOOD WHEN I TEST IT WITH 
     "info[0].firstname" but NOT with "info[1].firstname... info[2], etc...
    
    


    Text Document:

    5
    Llewellyn Mark
    1 15 19 26 33 46
    Young Brian
    17 19 33 34 46 47
    Cazalas Jonathan
    1 4 9 16 25 36
    Siu Max
    17 19 34 46 47 48
    Balci Murat
    5 10 17 19 34 47


    NOTE:
    I am simply trying to scan all the last names and first names at once and then have access to each last or first name. After attempting to come up with the code, I was trying to test it by printing out different last names that were stored in the array. Please HELP.
    Last edited by matthayzon89; 09-02-2010 at 01:56 PM.

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,246
    You need to tell us what part of your application is not working the way you expect.
    bit∙hub [bit-huhb] n. A source and destination for information.

  3. #3
    Registered User
    Join Date
    Feb 2010
    Posts
    244
    I edited my code and added some comments explaining what is not working. Thanks for the reply.

    So, basically when I scan the FIRST firstname and lastname on my .txt document and try to print it out, it works!

    When I try to scan my second, third, fourth, etc... firstname and lastname AND print them out it does not work.

    The way I try to access the first, firstname and lastname is first info[0].firstname and info[0].lastname

    therefore, the second firstname and lastname should be info[1].firstname and info[1].lastname But it doesn't work...it does not read the correct data and THATS what I need help with..

    Thanks again! (I'm a bit frustrated)
    Last edited by matthayzon89; 09-02-2010 at 02:36 PM.

  4. #4
    msh
    msh is offline
    Novice
    Join Date
    Jul 2009
    Posts
    568
    Do you think it should automagically skip the line containing numbers? (Now, I didn't test this, but it does seem wrong.)

    Furthermore, your lotto structure has an array for 5 int's, then each player has 6 numbers. What's up with that?

  5. #5
    Registered User
    Join Date
    Feb 2010
    Posts
    244
    Quote Originally Posted by msh View Post
    Do you think it should automagically skip the line containing numbers? (Now, I didn't test this, but it does seem wrong.)

    Furthermore, your lotto structure has an array for 5 int's, then each player has 6 numbers. What's up with that?
    Well, I thought since I was searching for sting using '%s' then it would skip the integers.... I guess I am wrong, do you have any idea on how to skip the integers and store the next name on the list?

    array of size 5= slot 0, 1, 2, 3, 4, 5 which equals 6, right?

    I appreciate the reply.

  6. #6
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    An array of size 5, i.e. declared with [5], has five elements. These elements are 0, 1, 2, 3, and 4. Such an array does not have an element [5] that you can access. Another example: in order to store six numbers you need an array of size 6, which you declare as [6]; to access these elements you start at 0 and keep counting up until you have addressed all six of your elements, which means that the last valid index is at 5.

    When you're reading from a file, it's just like reading the user's input. All characters that are present in the file must be processed in the order they are received. "%s" instructs fscanf() to try to interpret the next characters as a string. Basically there's a notion of a current position in the file, and as you read characters the position advances. You can interpret the characters as a string, or a number, or whatever else you like.

    Here's an example. Suppose you pass fscanf() a %d, asking it to interpret characters as an integer. If the stream (like a file or user input) contains "123\netc", fscanf() will read the '1' and '2' and '3', do some multiplication and give you the number 123, leaving "\netc" in the input stream. If you then called fscanf() with %d again it would skip the '\n' (scanf() functions skip whitespace when looking for numbers), then hit the 'e' and decide that this character can't be interpreted as part of a number. fscanf() will fail and return an error code to you. If you ignore the error code you'll be using an uninitialized variable in your program.

    Notice how I said fscanf() skips over whitespace when it's looking for numbers (and strings, etc.). This means that once it fails to find an item once it's hard to recover from the error and keep going, because you don't really know where on a line you are, whether the line is malformed, etc. For this reason it's often suggested that you read in entire lines at once with fgets(), and then attempt to process the lines individually with sscanf(). If any line fails to be in the correct format, you can keep going and continue to process further lines.

    Anyway, here's an example of the kind of code you could use. (I've assumed that the number at the beginning of the file does not exist or has already been processed, because it's not actually necessary.)
    Code:
    FILE *fp = fopen( /* ... */ );
    char line[BUFSIZ];
    int count = 0;
    
    while(fgets(line, sizeof line, fp)) {
        count ++;
        if(count % 2 == 1) { /* odd-numbered line, must be a name */
            char first[BUFSIZ], last[BUFSIZ];
            if(sscanf(line, "%s%s", first, last) == 2) {
                /* since sscanf() returned 2, both items were successfully read */
    
                /* (names printed in square brackets to make the contents
                    of the variables obvious) */
                printf("Hello, [%s] [%s].\n", first, last);
            }
            else {
                printf("Error processing line %d: didn't look like a name\n", count);
            }
        }
    }
    fgets() returns NULL if it fails to read a line (which normally happens at the end of the file); hence, the while loop executes once per line and allows you to deal with it. On odd-numbered lines (where the first line is line 1), you expect to find a name, so the code uses sscanf() to pull information out of the line and into two strings (first and last). Note that there are two format specifiers given, "%s%s" (and there is no space between them -- as I said before *scanf() skip whitespace when converting input into the expected format). sscanf() returns the number of format specifiers it was able to successfully satisfy; in this case, 2 if both strings were present on the line, 1 if only one of them was, and 0 if neither were.

    Anyway, CBoard has logged me out now and I'm tired of typing anyway. If you want to know more, try searching the boards or ask another question.

    [edit] One other thing I forgot to mention: you should fclose() a file when you're done with it. [/edit]
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  7. #7
    Registered User
    Join Date
    Feb 2010
    Posts
    244
    Thanks for the reply. I have not gotten to fgets yet and I don't think we are expected to use it. It seems far more complicated then what I currently know and would probably take me a long long time to learn and understand good enough to apply it to the program I need to turn in tomorrow:/ Is there any other way to solve this problem along the lines in which I started?

    Thanks

  8. #8
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    Of course there are other ways to solve this problem. I suppose the simplest is to just read all the data into your structure at once, including names and numbers. After you read in the first and last name as you have done, read in the remaining six numbers into ticket_num[5] and winnings respectively of the current structure. That way your fscanf() %s%s will always be at a first/last name pair.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help in C programming (too lazy)
    By cwillygs in forum C Programming
    Replies: 12
    Last Post: 04-20-2010, 01:23 AM
  2. Need help with linked list sorting function
    By Jaggid1x in forum C Programming
    Replies: 6
    Last Post: 06-02-2009, 03:14 AM
  3. Bitmasking Problem
    By mike_g in forum C++ Programming
    Replies: 13
    Last Post: 11-08-2007, 12:24 AM
  4. HUGE fps jump
    By DavidP in forum Game Programming
    Replies: 23
    Last Post: 07-01-2004, 11:36 AM
  5. gcc problem
    By bjdea1 in forum Linux Programming
    Replies: 13
    Last Post: 04-29-2002, 07:51 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21