Thread: Errors in reading a file

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    17

    Errors in reading a file

    Hi , i am trying to open a file which contains strings and numbers. I have to extract the numbers and find their average. The code isnt working, it seg faults when i run it with a text file.

    All help is appreciated.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    #define ROWS 3
    #define COLUMNS 3
    
    int
    main (int argc, char *argv[])
    {
    
      FILE *fp;
      char array[ROWS][COLUMNS];
    //  int *ptr[ROWS]
      int i, sum = 0;
      int avg[ROWS], nums[3];
      int cnt;
    
      //open the file for reading
      if (argc > 1)
        {
    
          fp = fopen (argv[1], "r");
          while (fgets (array[i], COLUMNS, fp) != NULL)
            {
    
    //        ptr[i] = array[i];
    
              if (scanf ("%d%d%d", &nums[0], &nums[1], &nums[3]) == 3)
                {
                  for (cnt = 0; cnt < 3; cnt++)
                    {
                      sum += nums[cnt];
                    }
                  avg[i] = (sum / 3);
                  sum = 0;
                  i++;
                }
            }
          printf ("%d", avg[i]);
        }
      return 0;
    }

  2. #2
    Registered User
    Join Date
    Jan 2010
    Posts
    34
    Code:
              if (scanf ("%d%d%d", &nums[0], &nums[1], &nums[3]) == 3)
    Is not scanf for scanning from input?
    if you want to scan a char string you must use sscanf.
    Or better, you can use directly a fscanf (from online sample):
    Code:
    /* fscanf example */
    #include <stdio.h>
    
    int main ()
    {
      char str [80];
      float f;
      FILE * pFile;
    
      pFile = fopen ("myfile.txt","w+");
      fprintf (pFile, "%f %s", 3.1416, "PI");
      rewind (pFile);
      fscanf (pFile, "%f", &f);
      fscanf (pFile, "%s", str);
      fclose (pFile);
      printf ("I have read: %f and %s \n",f,str);
      return 0;
    }

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You forgot to initialize i to 0.

  4. #4
    Registered User
    Join Date
    Oct 2010
    Posts
    17
    Hi

    I have made those changes. Thanks for that, however i get a random value... which i cant figure out why.

    So for the avg value i cant seem to get the right answer when priting it out.

    Thanks for your help.

  5. #5
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Code:
              if (scanf ("%d%d%d", &nums[0], &nums[1], &nums[3]) == 3)
    Shouldn't that be &nums[2] instead of 3 ... by the earlier defintion of nums, 3 is out of bounds

  6. #6
    Registered User
    Join Date
    Oct 2010
    Posts
    17
    Yes

    I have made that change. However, i still get the random answer.
    Thanks

  7. #7
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Good eye, CT!

  8. #8
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Adak View Post
    Good eye, CT!
    thanks... just dumb luck though.

  9. #9
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You're going to have to post up the input file, and show us the random answer you're referring to. I don't see any other errors. It's time to run it on the data, I believe.

    @CT, you're just modest. Hell of an asset to this forum, imo.
    Last edited by Adak; 10-25-2010 at 03:05 AM.

  10. #10
    Registered User
    Join Date
    Oct 2010
    Posts
    17
    heres wha the file contains:

    Name one 10 points
    Name two 20 points
    Name three 30 points

    thats all it has- i am supposed to just caluclate the result of those 3 numbers

    Thanks

  11. #11
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    So a sample file might be:
    Code:
    Andy one 82
    Andy two 85
    Andy three 89
    Bill one 93
    Bill two 88
    Bill three 91
    for the first two students?

    Do you need to add scores from the keyboard, at all?

  12. #12
    Registered User
    Join Date
    Oct 2010
    Posts
    17
    ok for the file there will be 3 marks - just like that format.

    We are supposed to read that file - also there will only be 3 names not any more than that. Then we have to find the average of those.

    Thank You

  13. #13
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Okay, dokie! It's an odd format (and makes the logic here, a bit unusual, but Yokay!


    This is your program, with several tweaks.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    #define ROWS 3
    #define COLUMNS 50
    
    int
    main (int argc, char *argv[])
    {
    
      FILE *fp;
      char line1[COLUMNS];
      char names[ROWS][COLUMNS];
      int scores[ROWS][ROWS];
      int avg[ROWS];
      int i, sum;
      int length, j, k;
    
      printf("\n\n");
      //strcpy(argv[1], "sidak.txt");  //for debug only, in the IDE
      //open the file for reading
      if (argc > 1)
      {
        fp = fopen (argv[1], "r");
        i=j=sum=0;
        while((fgets (line1, COLUMNS, fp)) != NULL)
        {
          length=strlen(line1);
          if(line1[length-1]=='\n')
          line1[length-1]='\0';
          sscanf(line1, "%s %*s %d", names[i], &scores[i][j]);
          ++j;
          if(j>2) {
            j=0;
            ++i;
          }
        }
    /* for debug help only 
        for(i=0;i<ROWS;i++)  {
          printf("\n%15s", names[i]);
          for(j=0;j<ROWS;j++) {
            printf(" %3d", scores[i][j]);
          }
        }
    */    
        sum=0;
        for(j=0, k=0;j<i;j++) {
          sum=scores[j][0]+scores[j][1]+scores[j][2];
          avg[k++]=sum/3;
          sum=0;
        }
        for(i=0;i<ROWS;i++)  {
          printf("\n%15s    Scores:", names[i]); 
          for(j=0;j<ROWS;j++) 
            printf(" %3d", scores[i][j]);
          printf("   Average: %3d", avg[i]);
        }
      }
      fclose(fp);
      printf("\n\n\t\t\t    press enter when ready");
      (void) getchar();
      return 0;
    }
    Last edited by Adak; 10-25-2010 at 07:01 PM.

  14. #14
    Registered User
    Join Date
    Oct 2010
    Posts
    17
    Hi

    Ok. thanks alot for that.

    The output for some reason is a bit wierd.

    This is what i got"

    John Scores: 134513326 0 0 Average: 44837775
    Scores: 1 2140 -1208888536 Average: -1210418504
    Scores: -1208878320 134513326 -1210381684 Average: 13451334

    Is that the same as yours?

    Thanks

  15. #15
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Of course not: My output is:

    Code:
    
    
               Andy    Scores:  82  85  89   Average:  85
               Bill    Scores:  93  88  91   Average:  90
             Claire    Scores:  87  87  87   Average:  87
    
    			    press enter when ready
    Your data file seems to have a different name or contents than the one you OK'd for me to work with.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. sequential file program
    By needhelpbad in forum C Programming
    Replies: 80
    Last Post: 06-08-2008, 01:04 PM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM