Thread: make a polynomial from file (linked lists)

  1. #1
    Registered User
    Join Date
    May 2019
    Posts
    3

    make a polynomial from file (linked lists)

    im confused as to how to read a file line by line and store them in a linked list say:

    2 //2 cases- addition or expansion
    1 //case 1- addition
    4 //1st polynomial = 4 terms
    2 3 //2x^3
    4 6
    1 0
    4 5
    3 //2nd polynomial = 3 terms
    5 7
    3 2
    4 5

    below is my code so far but i just realized that it is not flexible especially when the first case is an expansion and then the addition case is just second


    Code:
    void createpoly(pnode **hptr, FILE **fptr){ 
        int coef, pow;
        int i, termcount, temptermcount;
        int count = 0;
    
    
        *hptr = (pnode *)malloc(sizeof(pnode)); 
        for(i = 0; fscanf(*fptr, "%d", &i) && !feof(*fptr); i++){
            if(count == 0){ 
                termcount = i; 
                temptermcount = i - 3; 
            }
            count++;
    
    
            pnode *temp = *hptr; 
            while(termcount > 0){ \
                // newnode = (pnode *)malloc(sizeof(pnode));
                while(temp->next != NULL){
                    temp = temp->next;
                }
    
    
                if(temp->next == NULL){
                    temp->next = (pnode *)malloc(sizeof (pnode));
                    fscanf(*fptr, "%d", &(temp->coef)); 
    
    
                    fscanf(*fptr, "%d", &(temp->pow));
                    temp->next->next = NULL; node
    
    
                }
    
    
                termcount --;
    
    
            }
    
    
            if(count == temptermcount){
                termcount = i;
            }
    
    
            while(termcount > 0){ //second termcount 
    
    
                while(temp->next != NULL){
                    temp = temp->next;
                }
    
    
                if(temp->next == NULL){
                    temp->next = (pnode *)malloc(sizeof (pnode));
                    fscanf(*fptr, "%d", &(temp->coef)); //input coef and power
                    fscanf(*fptr, "%d", &(temp->pow));
                    temp->next->next = NULL; //link last data to end empty node
    
    
                }
            termcount --;
            }   
    
    
        }
    
    
    }

  2. #2
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Sorry by my ignorance, but, in this context, what is an expansion and how do you differ it from an "addition"?
    And, maybe it would be easy to structure your inputs as:

    <num-of-polynomials>
    <poly1-nth-coef> <poly1-n-1th-coef> ... <poly1-1st-coef>
    <poly2-nth-coef> <poly2-n-1th-coef> ... <poly2-1st-coef>
    ...

    Example:

    2
    2 3
    3.14 7.2 1.3

    2 polynomials: First: 2x¹+3x⁰; second: 3.14x²+7.2x¹+1.3x⁰

    To mount the lists you only need to allocate the nodes and insert them at list head.

    if you need to add comments to your file, consider reading the line with fgets() or getline() and strip everything after '//' (or whatever you use as comment mark)... and, of course, ignore empty lines...

  3. #3
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Do you really need linked lists? Do you really need to inform the number of polynomials and the number of coefficients?
    Here's an example using a file like this:
    Code:
    # test.txt: 3 Polynomials defined below:
    1 2 3
    3.14 2.72 10 1
    
    # line above is blank
    3 2 1 4 # line with polynomial and commentary.
    And here's a program to parse this:
    Code:
    // sys.c
    //
    // This program reads lines, ignoring empty ones and comments (marked with #)...
    // MORE work needed. For instance, to check if a line has an invalid syntax.
    //
    
    // definition needed for GNU's basename() routine.
    #define _GNU_SOURCE
    #include <stdio.h>
    #include <stdlib.h> // realloc() and free(). and EXIT_??? constants.
    #include <string.h> // basename(), strtok(), strchr().
    
    // "list" of coefficients.
    typedef struct coeff_T
    {
      unsigned int numcoeffs;
      double *coeffs;
    } coeff_T;
    
    // Get coefficients from a line.
    int get_coeffs( coeff_T *, char *, unsigned int );
    
    int main( int argc, char *argv[] )
    {
      FILE *f;
      char *line;
      size_t line_size;
      coeff_T *polys_listp = NULL;
      unsigned int numpolys = 0, i;
    
      // test command line arguments.
      if ( argc != 2 )
      {
        fprintf( stderr, "Usage: %s <file>\n", basename( *argv ) );
        return EXIT_FAILURE;
      }
      
      // tries to open the input file.
      if ( ! ( f = fopen( *++argv, "r" ) ) )
      {
        fprintf( stderr, "ERROR: Cannot open '%s' file.\n", *argv );
        return EXIT_FAILURE;
      }
    
      // Read the lines (dynamic allocated)...
      line = NULL;
      line_size = 0;
      while ( getline( &line, &line_size, f ) != -1 )
      {
        coeff_T coeffs;
    
        // if there are coefficients, update the polynomials list.
        if ( get_coeffs( &coeffs, line, numpolys + 1 ) )
        {
          coeff_T *p;
    
          // Increase polynomials list size.
          if ( ! ( p = realloc( polys_listp, sizeof(coeff_T)*(numpolys + 1) ) ) )
          {
            fputs( "ERROR: Cannot reallocate polynomials list.\n", stderr );
            return EXIT_FAILURE;
          }
          polys_listp = p;
          polys_listp[numpolys++] = coeffs;
        }
    
        // free the line and prepare for the next one.
        free( line );
        line = NULL;
        line_size = 0;
      }
    
      fclose( f );
    
      // Show the polynimials. Expoents in reverse order.
      for ( i = 0; i < numpolys; i++ )
      {
        unsigned int j;
    
        printf( "%u: ", i + 1 );
        for ( j = 0; j < polys_listp[i].numcoeffs; j++ )
          printf( "%gx^%u ", polys_listp[i].coeffs[j], polys_listp[i].numcoeffs - j - 1 );
        putchar('\n');
      }
    
      return EXIT_SUCCESS;
    }
    
    // numpoly used only to report error...
    int get_coeffs( coeff_T *coeffsp, char *linep, unsigned int numpoly )
    {
      double *q;
      char *p;
      double n;
    
      coeffsp->numcoeffs = 0;
      coeffsp->coeffs = NULL;
    
      // strip comments...
      if ( p = strchr( linep, '#' ) ) 
        *p = '\0';
    
      // get the tokens, ignoring spaces...
      p = strtok( linep, " \t" );
      while ( p )
      {
        // if there are no numeric values, exit loop.
        if ( sscanf( p, "%lf", &n ) != 1 )
          break;
    
        // Increase the coefficiets list size.
        if ( ! ( q = realloc( coeffsp->coeffs, sizeof (double) * (coeffsp->numcoeffs + 1) ) ) )
        {
          fprintf( stderr, "ERROR: Cannot allocate coefficients list (polynomial #%u).\n", numpoly );
          exit(EXIT_FAILURE);
        }
        coeffsp->coeffs = q;
    
        q[coeffsp->numcoeffs++] = n;
    
        // get the next token.
        p = strtok( NULL, " \t" );
      }
    
      // 0 means no coeficiets...
      return coeffsp->numcoeffs;
    }
    Compiling, linking and running:
    Code:
    $ cc -o sys sys.c
    $ ./sys test.txt
    1: 1x^2 2x^1 3x^0 
    2: 3.14x^3 2.72x^2 10x^1 1x^0 
    3: 3x^3 2x^2 1x^1 4x^0
    Last edited by flp1969; 05-13-2019 at 10:49 AM.

  4. #4
    Registered User
    Join Date
    May 2019
    Posts
    3
    Sorry for the late reply, I was confused on how fscanf reads integers from files(the file is required) so i changed my code to be more flexible but now it produces segfault

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    
    typedef struct term_tag{
        int coef;
        int exponent;
        struct term_tag *next;
    }pnode;
    
    
    void createpoly();
    
    
    
    
    
    
    int main(){
        pnode *poly1 = (pnode *)malloc(sizeof(pnode));
        pnode *poly2 = (pnode *)malloc(sizeof(pnode));
     
    
    
        FILE *fp;
    
    
        fp = fopen("input.txt","r"); 
    
    
        // CASE COUNT 
        if(fp != NULL) createpoly(poly1, poly2, fp);
    }
    
    
    
    
    void createpoly(pnode **pptr1, pnode **pptr2, FILE **fptr){
        int case_count, case_num, term_count;
        
        fscanf(*fptr,"%d",&case_count);
    
    
        // CASES     
          while(case_count > 0){
              fscanf(*fptr, "%d", &case_num); //read line then move to new line
                  if(case_num == 1){ //case 1 
                      fscanf(*fptr, "%d", &term_count); //store line content(ie term count to var)
    
    
                      pnode *temp = *pptr1; 
                      while(term_count > 0){
                         while(temp->next != NULL){ //traverse list 
                             temp = temp->next;
                        }
                          if(temp->next == NULL){ //add to tail
                              temp->next = (pnode *)malloc(sizeof (pnode));
                            fscanf(*fptr, "%d", &(temp->coef)); //input coef and power
                            fscanf(*fptr, "%d", &(temp->exponent));
                            temp->next->next = NULL; //link last data to end empty node
    
    
                          }
                      term_count--;
                      }
    
    
                      
                      fscanf(*fptr, "%d", &term_count); //store line content(ie term count to var)
    
    
                      pnode *temp2 = *pptr2; //traverse list
                      while(term_count > 0){
                         while(temp2->next != NULL){
                             temp2 = temp2->next;
                        }
                          if(temp2->next == NULL){ //add to tail
                              temp2->next = (pnode *)malloc(sizeof (pnode));
                            fscanf(*fptr, "%d", &(temp2->coef)); //input coef and power
                            fscanf(*fptr, "%d", &(temp2->exponent));
                            temp->next->next = NULL; //link last data to end empty node
    
    
                          }
                      term_count--;
                      }
    
    
                  }
              case_count--;
          }                                                                                    
       
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 07-06-2013, 08:22 AM
  2. Cannot make linked lists work
    By zephyrcat in forum C++ Programming
    Replies: 4
    Last Post: 01-16-2008, 07:04 PM
  3. Replies: 5
    Last Post: 08-01-2007, 06:17 AM
  4. linked lists of a polynomial
    By Unregistered in forum C++ Programming
    Replies: 4
    Last Post: 02-11-2002, 07:51 PM
  5. linked lists of a polynomial
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 02-11-2002, 06:44 PM

Tags for this Thread