Thread: Read Input file, Calculate data, Write Output file

  1. #1
    Registered User
    Join Date
    Jul 2021
    Posts
    5

    Read Input file, Calculate data, Write Output file

    Good day guys,

    I am really need help from anyone who knows how to write C program. I've spent 4 days trying to write the C program but failed...Can anyone help me on this? I am really lost and don't know what to do.


    I only can get this to display the data from input file.

    Code:
    Code:
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <conio.h>
    
    
    int main()
    {
        
        struct StudentData StdData;
        int i, j, n;
        float Total;
        char std[100];
        
        
        FILE *fListData;
        FILE *fResult;
        
        fListData = fopen("Project.txt", "r");
        fResult = fopen("FinalResult.txt", "w");
        
        if (fListData == NULL| fResult == NULL)
        {
            printf("File could not be opened \n");
            return 0;
        }
        
        while (fgets(std, sizeof(std), fListData))
        {
            printf("%s", std);
        }
    
        
        fclose(fResult);
        fclose(fListData);
        
        return 0;
    }
    Attached Images Attached Images Read Input file, Calculate data, Write Output file-pic-2-jpg Read Input file, Calculate data, Write Output file-pic-1-jpg 

  2. #2
    Registered User
    Join Date
    Apr 2021
    Posts
    12
    You didn't say what the problem is, but it's clear that your code won't even compile. The structure tag "StudentData" is not defined anywhere. Before your first use (I usually put type definitions after any #include's but before any functions) you should add something like:
    Code:
    typedef struct StudentData
    {
        char  name[42];
        char  id[9]; // 8 chars + delim
        int tests[3];
        int homework[4]
        //...etc.
    } StudentData;
    Or, you could just comment out the declaration of that `StdData` variable, since you're not using it (yet).

    Then you can work on seeing that you are reading and interpreting the input file properly. Don't worry about structs or output files yet..just write code to read in information for one student and display it on the terminal. Once you know your input is working, then start working on formatting the output.

    Try to practice that idea: Write a part of the program, fully test it, then move on to the next part. Two huge benefits are that it cuts down on complexity, since each step is just writing a small program or adding a small change to an existing program); and that when something goes wrong it's usually in the small bit that you just added so you don't have to scour the whole program for it.

  3. #3
    Registered User
    Join Date
    Jul 2021
    Posts
    5
    Hi,

    Thanks for the reply.

    I've make a new code just to display the data from the input file. The previous code messy and deleted all. Here the code that I write;

    Code:
        FILE *fListData;
        FILE *fResult;
        
        fListData = fopen("Project.txt", "r");
        fResult = fopen("FinalResult.txt", "w");
        
        if (fListData == NULL | fResult == NULL)
        {
            printf("File could not be opened \n");
            return 0;
        }
        
        char std[100];
        
        while (fgets(std, sizeof(std), fListData))
        {
            printf("%s", std);
        }
        
        
        fclose(fResult);
        fclose(fListData);
    How can I extract several data from the input file i.e. all the marks? My final output should be Name of the student, their total marks and grade.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    Before you start trying to store and analyse your data, you need to make sure you can reliably parse the line.

    How you do this depends somewhat on how the fields are separated (fuzzy pictures of your files don't tell us anything useful).

    The tricky part is dealing with names that have no consistent formatting.
    Code:
    #include<stdio.h>
    #include<string.h>
    
    size_t strlcpy(char *dest, const char *src, size_t size) {
      strncpy(dest,src,size-1);
      dest[size-1] = '\0';
    }
    
    int main()
    {
      char line1[] = "Abdul Rouf b. Ruslan          AK021425    47   17   50   10   10   10   10   68\n";
      char line2[] = "Abdul Rouf b. Ruslan\tAK021425\t47\t17\t50\t10\t10\t10\t10\t68\n";
      char name[100], id[20];
    
      // 1
      sscanf(line1,"%30s%s",name,id);   // doesn't work
      printf(">>%s<< >>%s<<\n",name,id);
    
      // 2
      strlcpy(name,line1,30);     // copy name manually, but with lots of extra spaces
      sscanf(&line1[30],"%s",id); // start sscanf in the middle of line
      printf(">>%s<< >>%s<<\n",name,id);
    
      // 3
      sscanf(line2,"%[^\t]%s",name,id);
      printf(">>%s<< >>%s<<\n",name,id);
    
      return 0;
    }
    
    
    $ gcc foo.c
    $ ./a.out 
    >>Abdul<< >>Rouf<<
    >>Abdul Rouf b. Ruslan         << >>AK021425<<
    >>Abdul Rouf b. Ruslan<< >>AK021425<<
    Here are two examples of an input line
    line1 has all the columns of data padded with spaces.
    line2 has all the columns of data separated by tab characters.

    So what you need to do is something like this initially.
    Code:
    while (fgets(std, sizeof(std), fListData))
    {
      char name[100], id[20];
      sscanf(std,"%[^\t]%s",name,id);
      printf(">>%s<< >>%s<<\n",name,id);
    }
    Experiment with the various ideas to get the name and ID copied out of the input line and into variables of your choice.

    When you've got the name and ID being extracted successfully, try adding the extraction of T1,T2,T3 as well.

    Getting the rest of the line is easy, an appropriate number of %d conversions will deal with those just fine.
    The real trick is getting a reliable extraction of name and ID.

    When your data extractor is working, then you can think about your StudentData and how to store, analyse and present your results.

    > if (fListData == NULL | fResult == NULL)
    This should use the || operator, not the | operator.
    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.

  5. #5
    Registered User
    Join Date
    May 2012
    Posts
    505
    University professors shouldn't give exercises like this.

    C doesn't have good facilities for parsing input. You have to write from scratch on the top of low level functions. To do a really solid job is hard.

    For instance, is the header fixed, or could the columns be shuffled about? What are you meant to do on bad inputs? There are many questions which are being skated over.


    Your best bet is probably to start by writing a loop that opens the file, reads it line by line with a call to fgets(), and prints the lines out inside two asterisks (to show that you've actually processed the data).

    The build up. Discard the first line, and use sscanf() to extract the fields, as explained by others. The take out the interleaved printf() and output yur results after parsing the whole file.
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


  6. #6
    Registered User
    Join Date
    Jul 2021
    Posts
    5
    Here the result the I get:

    Read Input file, Calculate data, Write Output file-screenshot-jpg

    by adding the sscanf to scan the name and id;

    Code:
    char StdName[100];
        char StdID[20];
        
        fListData = fopen("Project1.dat", "r");
        
        if (fListData == NULL)
        {
            printf("File could not be opened\n");
            return 0;
        }
            
        while (fgets(std, sizeof(std), fListData))
        {
            sscanf(std,"%[^\t]%s", StdName, StdID);
            printf("%s %s\n", StdName, StdID);
        }
        
        
        return 0;
    }

  7. #7
    Registered User
    Join Date
    Jul 2021
    Posts
    5
    I'm also quite shocked when our professor gave us this exercise since I'm still new to C Programming and still learning how to read the code yet given this task.

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    You need to upload / attach your project1.dat (Valid file extensions: bmp c cc cpp cxx doc gif h hpp hxx jpe jpeg jpg pdf png psd txt xls zip), so rename it as a .txt file.

    That's the only way to make sense of what's in the file compared to how you're trying to parse it.
    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.

  9. #9
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    FYI: The logical or operator is "||" in C programming the "|" is bit wise or which you should not be using in this program.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  10. #10
    Registered User
    Join Date
    Jul 2021
    Posts
    5
    Good day,

    I have make a new coding to calculate the data. But now I'm not taking the data from the input file. However, I can't run my program due to some error that I little understand and would like to seek some help on checking my coding. Thank you.

    Code:
     
    struct StudentData Std[50];
     {  
        int T1, T2, T3, PRJ; 
        float HW1, HW2, HW3, HW4, HW5;
        float TotalT, TotalH, TotalP;
        float Marks; 
        int i, n;
    }  
      
        printf("Please Enter Students Details:\n\n");
        
        for(i=0; i<n; i++)
        {
            printf("STUDENT NAME: ");
            scanf("%s", &Std[i].Stdname);
            printf("STUDENT ID:  ");
            scanf("%s", &Std[i].StdID);
            
            print("PLEASE PROVIDE STUDENT CARRY MARKS:\n");
            
            printf("TEST 1: ");
            scanf("%d", &Std[i].T1);
            printf("TEST 2: ");
            scanf("%d", &Std[i].T2);
            printf("TEST 3: ");
            scanf("%d", &Std[i].T3);
            
            printf("HOMEWORK 1: ");
            scanf("%.2f", &Std[i].HW1);
            printf("HOMEWORK 1: ");
            scanf("%.2f", &Std[i].HW2);
            printf("HOMEWORK 1: ");
            scanf("%.2f", &Std[i].HW3);
            printf("HOMEWORK 1: ");
            scanf("%.2f", &Std[i].HW4);
            printf("HOMEWORK 1: ");
            scanf("%.2f", &Std[i].HW5);
    
            
            printf("PROJECT:");
            scanf("%d", &Std[i].PRJ);
            
            TotalT = (Std[i].T1+Std[i].T2+Std[i].T3)*0.2;
            printf("TOTAL MARKS FOR TEST: %.2f/n", TotalT);
            TotalH = (Std[i].HW1 + Std[i].HW2 + Std[i].HW3 + Std[i].HW4+Std[i].HW5);
            printf("TOTAL MARKS FOR HOMEWORK: %.2f\n", TotalH);
            TotalH = PRJ*0.3;
            printf("TOTAL MARKS FOR PROJECT: %.2f", TotalP);
            Marks = TotalT + TotalH + TotalP;
            printf("Overall Marks: ", &Marks);
            scanf("%.2f", Std[i].Total);
        }
        
        for(i=0; i<n; i++)
        {
            if(Std[i].Total >=90)
            {
                Std[i].Grade = 'A+';
            }
            else if(Std[i].Total >=80)
            {
                Std[i].Grade = 'A';
            }
            else if(Std[i].Total >=75)
            {
                Std[i].Grade = 'A-';
            }
            else if(Std[i].Total >=70)
            {
                Std[i].Grade = 'B+';
            }
            else if(Std[i].Total >=65)
            {
                Std[i].Grade = 'B';
            }
            else if(Std[i].Total >=60)
            {
                Std[i].Grade = 'B-';
            }
            else if(Std[i].Total >=55)
            {
                Std[i].Grade = 'C+';
            }
            else if(Std[i].Total >=50)
            {
                Std[i].Grade = 'C';
            }
            else if(Std[i].Total >=45)
            {
                Std[i].Grade = 'C-';
            }
            else if(Std[i].Total >=40)
            {
                Std[i].Grade = 'D+';
            }
            else if(Std[i].Total >=35)
            {
                Std[i].Grade = 'D';
            }
            else if(Std[i].Total >=30)
            {
                Std[i].Grade = 'D-';
            }
            else
            {
                Std[i].Grade = 'E';
            }
            
        }
        
        for (i=0; i<70; i++)
        printf("_");printf("\n");
        printf("NAME\t\t\tID\tTOTALMARKS\tGRADE\n");
        
        for(i=0; i<70; i++)
        printf("_");printf("\n");
        
        for(i=0;i<n;i++)
            {
            printf("%s\t\t\t%s\t%.2f\t%s", Std[i].Stdname, Std[i].StdID, Std[i].Total, Std[i].Grade);
               }
               
       for(i = 0;i<70;i++)
       printf("_");printf("\n");
       
       getch();
       
       return 0;
    Last edited by Ron09sime; 07-04-2021 at 02:13 AM.

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    As I've already explained, you're not going to read a name like "Abdul Rouf b. Ruslan" with the %s format in scanf.

    But then again, you charged ahead by trying to write the whole program without understanding how to do the first step.
    So basically, you wound up with a mess of code that doesn't work.

    > for(i=0; i<n; i++)
    What value is n here?
    You've only declared it, you haven't initialised it.

    > Std[i].Grade = 'A+';
    Characters are single characters.
    If you want to store more than one, it has to be a string like "A+".
    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. Replies: 16
    Last Post: 12-08-2017, 08:44 AM
  2. How to write and read object data from a file ?
    By NomanProdhan in forum C++ Programming
    Replies: 4
    Last Post: 07-12-2017, 11:15 PM
  3. can't write .bmp header or image data to output file
    By MWJack in forum C Programming
    Replies: 0
    Last Post: 12-12-2015, 02:05 AM
  4. Replies: 2
    Last Post: 08-30-2014, 11:07 PM
  5. Replies: 6
    Last Post: 12-06-2013, 11:39 PM

Tags for this Thread