Thread: Why isn't my program reading my file properly?

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    31

    Why isn't my program reading my file properly?

    Hi all, I'm trying to get my program to read from a file that has both characters and integers (names and scores in a class). The file is set up like this with 30 names and scores:

    Elizabeth 74

    How do I make my program print this as shown? Every time I try to do it I get a whole bunch of weird characters (like a bunch of Os or Hs all in a line), and it's driving me mad. I even tried replacing all the names and scores in my file with just letter grades to test it, and it still didn't work properly. What am I doing wrong? I checked the FAQ, but it didn't mention anything like this. Also, is it possible to set up an array with the names and scores just like I've shown up there? I need to use the scores later in my program to calculate the class average, the highest score, and the lowest score. I'll provide the code I have now (which isn't much, admittedly) as well as the text file.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <stdbool.h>
    
    #define ARRAY_SIZE 30
    
    int main(void)
    {
        FILE* spStudents;
        float average = 0;
        char students;
        int scores;
        
        printf("Welcome! This program will read a text file containing names\n");
        printf("and scores of 30 students enrolled in a class. The program will\n");
        printf("arrange the list by score, find the class average, find the\n");
        printf("student with the lowest score, and find the student with\n");
        printf("the highest score.\n\n");
        
        spStudents = fopen("L:\\CIS 161\\Chapter VIII pt 1\\students.txt", "r");
        if (spStudents == NULL)
           {
             printf("Error opening students.txt for reading\n");
             exit (100);
           }
           
        printf("Here are the students and scores unsorted:\n");  
        
        fclose(spStudents);
          
      system("PAUSE");	
      return 0;
    }
    Here are the contents of my text file (these are all made up names and scores, by the way):

    Brendon 82
    Abigail 77
    Ethan 72
    Madeline 88
    Caleb 90
    Connor 69
    Emma 71
    Jacob 80
    Jack 91
    Elizabeth 74
    Andrew 84
    Gabriel 92
    Chloe 93
    Ian 73
    Isaac 89
    Claire 98
    Evan 75
    Rachel 85
    David 86
    Carly 78
    Jake 79
    Amber 66
    Henry 81
    Aubrey 70
    Julianna 83
    Hunter 68
    Joseph 62
    Lucy 99
    Erin 59
    Jason 94

  2. #2
    int x = *((int *) NULL); Cactus_Hugger's Avatar
    Join Date
    Jul 2003
    Location
    Banks of the River Styx
    Posts
    902
    Ok, I'll bite.

    As far as I can tell, your code compiles and runs, with no bugs. It also doesn't do anything, and makes no attempt at what you say it should do. It also doesn't exhibit the erroneous behavior that you claim it should... so:

    • Are you sure you've posted the correct source?
    • Have you tried compiling and running the source that you've posted?
    long time; /* know C? */
    Unprecedented performance: Nothing ever ran this slow before.
    Any sufficiently advanced bug is indistinguishable from a feature.
    Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
    The best way to accelerate an IBM is at 9.8 m/s/s.
    recursion (re - cur' - zhun) n. 1. (see recursion)

  3. #3
    Registered User NeonBlack's Avatar
    Join Date
    Nov 2007
    Posts
    431
    Use a function such as fscanf to actually read from the file.
    I copied it from the last program in which I passed a parameter, which would have been pre-1989 I guess. - esbo

  4. #4
    Registered User
    Join Date
    Apr 2008
    Posts
    31
    Quote Originally Posted by Cactus_Hugger View Post
    Ok, I'll bite.

    As far as I can tell, your code compiles and runs, with no bugs. It also doesn't do anything, and makes no attempt at what you say it should do. It also doesn't exhibit the erroneous behavior that you claim it should... so:

    • Are you sure you've posted the correct source?
    • Have you tried compiling and running the source that you've posted?
    Yes and yes.

    I added this a little while ago, which is giving me the weird results:
    Code:
        printf("Here are the students and scores unsorted:\n");  
        fscanf(spStudents, "%c %d", &students, &scores);
        printf("%c %d\n", &students, &scores);
        
        fclose(spStudents);
    Here is what it's giving me:

    Welcome! This program will read a text file containing names
    and scores of 30 students enrolled in a class. The program will
    arrange the list by score, find the class average, find the
    student with the lowest score, and find the student with
    the highest score.

    Here are the students and scores unsorted:
    o 2293608
    Press any key to continue . . .

    I tried it with a while loop as well, but all it did was give me the same result 30 times.

  5. #5
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    &#37;c reads 1 char
    %s reads unknown number of chars till it encounters whitespace or EOF
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  6. #6
    Registered User
    Join Date
    Apr 2008
    Posts
    31
    Okay, I did a bit more work, and it's displaying all the names and scores right, but I'm having problems figuring out how to keep a total of all the scores so I can use them to find the average and who has the highest and lowest scores. Here's my code so far:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <stdbool.h>
    
    #define ARRAY_SIZE 30
    
    int main(int argc, char *argv[])
    {
        FILE* spStudents;
        int average;
        char buffer[10001];
        char student[ARRAY_SIZE];
        int score;
        int sum;
        int target;
        
        printf("Welcome! This program will read a text file containing names\n");
        printf("and scores of 30 students enrolled in a class. The program will\n");
        printf("find the class average, find the student with the lowest\n");
        printf("score, and find the student with the highest score.\n\n");
        
        spStudents = fopen("L:\\CIS 161\\Chapter VIII pt 1\\students.txt", "r");
        if (spStudents == NULL)
           {
             printf("Error opening students.txt for reading.\n");
             exit (100);
           }
        
        fgets(buffer, 10000, spStudents);
        
        printf("Here are the names and scores:\n");
        while(feof(spStudents) == 0)
        {
           sscanf(buffer, "&#37;s%d", student, &score);
           printf("%s %d\n", student, score);
           fgets(buffer, 10000, spStudents);
        }    
        score += sum;
        average = sum / 30;
        printf("\nThe class average is: %d\n", &average);
        if (score == 99)
           {
              printf("The person with the highest score is: %s\n", &student);
           }
        if (score == 59)
           {
              printf("The person with the lowest score is: %s\n\n", &student);
           }
        printf("If you're looking for a particular score, please enter it, and\n");
        printf("I'll tell you if someone has that score: ");
        scanf("%d", &target);
        if (target == score)
           {
              printf("%s has that score!\n", &student);
           }
        if (target != score)
           {
              printf("Sorry, no one has that score.\n");
           }
        
        fclose(spStudents);
          
      system("PAUSE");	
      return 0;
    }

  7. #7
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    score += sum;
    you want it oppposite

    also sum should be initialized before loop
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  8. #8
    Registered User
    Join Date
    Apr 2008
    Posts
    31
    Quote Originally Posted by vart View Post
    score += sum;
    you want it oppposite

    also sum should be initialized before loop
    Alright, I did that, but it's still giving me a huge number for some reason.

    I did the math myself, and sum is supposed to be equal to 2408, so the average is supposed to be about 80. When I run the program, it gives me an average of 2293608, which is obviously WAY off.

  9. #9
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    you did one thing or both from suggested?
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  10. #10
    Registered User
    Join Date
    Apr 2008
    Posts
    31
    Quote Originally Posted by vart View Post
    you did one thing or both from suggested?
    Both. Here's the code I have now:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define ARRAY_SIZE 30
    
    int main(int argc, char *argv[])
    {
        FILE* spStudents;
        int average;
        char buffer[10001];
        char student[ARRAY_SIZE];
        int score;
        int sum;
        int target;
        
        printf("Welcome! This program will read a text file containing names\n");
        printf("and scores of 30 students enrolled in a class. The program will\n");
        printf("find the class average, find the student with the lowest\n");
        printf("score, and find the student with the highest score. It will also\n");
        printf("let you type in a score and tell you whether or not someone\n");
        printf("has that score.\n\n");
        
        spStudents = fopen("L:\\CIS 161\\Chapter VIII pt 1\\students.txt", "r");
        if (spStudents == NULL)
           {
             printf("Error opening students.txt for reading.\n");
             exit (100);
           }
        
        fgets(buffer, 10000, spStudents);
        
        sum += score;
        
        printf("Here are the names and scores:\n");
        while(feof(spStudents) == 0)
        {
           sscanf(buffer, "%s%d", student, &score);
           printf("%s %d\n", student, score);
           fgets(buffer, 10000, spStudents);
        }    
        
        average = sum / 30;
        printf("\nThe class average is: %d\n", &average);
        if (score == 99)
           {
              printf("The person with the highest score is: %s\n", &student);
           }
        if (score == 59)
           {
              printf("The person with the lowest score is: %s\n\n", &student);
           }
        printf("If you're looking for a particular score, please enter it, and\n");
        printf("I'll tell you if someone has that score: ");
        scanf("%d", &target);
        if (target == score)
           {
              printf("%s has that score!\n\n", &student);
           }
        if (target != score)
           {
              printf("Sorry, no one has that score.\n\n");
           }
            
        fclose(spStudents);
          
      system("PAUSE");	
      return 0;
    }

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define ARRAY_SIZE 30
    
    int main(int argc, char *argv[])
    {
        FILE* spStudents;
        int average;
        char buffer[10001];
        char student[ARRAY_SIZE];
        int score;
        int sum;
        int target;
    /* It's always a good habit to initialize your variables. This code would give a runtime error in Visual Studio (which means you're doing
     something wrong). */
        
        printf("Welcome! This program will read a text file containing names\n");
        printf("and scores of 30 students enrolled in a class. The program will\n");
        printf("find the class average, find the student with the lowest\n");
        printf("score, and find the student with the highest score. It will also\n");
        printf("let you type in a score and tell you whether or not someone\n");
        printf("has that score.\n\n");
        
        spStudents = fopen("L:\\CIS 161\\Chapter VIII pt 1\\students.txt", "r");
        if (spStudents == NULL)
           {
             printf("Error opening students.txt for reading.\n");
             exit (100);
           }
        
        fgets(buffer, 10000, spStudents);
    /* You are lying to fgets. Your buffer is 10001 chars. Use sizeof(buffer) instead. */
    
        sum += score;
    /* You are trying to add a number into an unitialized variable from an unitialized variable. Result? Never what you expect. Initialize 
    both to 0 and maybe remove the line. */
        
        printf("Here are the names and scores:\n");
        while(feof(spStudents) == 0)
        {
           sscanf(buffer, "&#37;s%d", student, &score);
    /* Extremely unsafe. Read http://cpwiki.sf.net/Buffer_overrun */
    
           printf("%s %d\n", student, score);
           fgets(buffer, 10000, spStudents);
        }    
        
        average = sum / 30;
    /* Pointless. sum == 0 at this point */
    
        printf("\nThe class average is: %d\n", &average);
        if (score == 99)
           {
              printf("The person with the highest score is: %s\n", &student);
    /* Will not result in what you expect. Read http://cpwiki.sf.net/A_pointer_on_pointers */
           }
        if (score == 59)
           {
              printf("The person with the lowest score is: %s\n\n", &student);
    /* Same here. See above. */
           }
        printf("If you're looking for a particular score, please enter it, and\n");
        printf("I'll tell you if someone has that score: ");
        scanf("%d", &target);
        if (target == score)
           {
              printf("%s has that score!\n\n", &student);
           }
        if (target != score)
           {
              printf("Sorry, no one has that score.\n\n");
           }
            
        fclose(spStudents);
          
      system("PAUSE");	
      return 0;
    }
    See my comments.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

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. Totally confused on assigment using linked lists
    By Uchihanokonoha in forum C++ Programming
    Replies: 8
    Last Post: 01-05-2008, 04:49 PM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. reading text from a file into your program
    By deltabird in forum C++ Programming
    Replies: 1
    Last Post: 06-26-2003, 10:34 AM