Thread: Data not seeming to go to array

  1. #16
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    It's certainly is not done, but it's a start.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <string.h>
    #include <ctype.h>
    
    //#include "abundance_sorter.h"
    //#include "element_info.h"
    
    #define MAX 30
    
    
    //int decision;
    struct element {
      char name[40];
      double abun;
      //you can add wavelength or other data members here, easily. 
    };
    int abundance_sorter(struct element *);
    void printIt(struct element *elem, int);
    void sortIt(struct element *elem, int, char);
    void swap(struct element *elem, int, int);
    
    static void forcefloat(float *p);  //ignore this!
    
    int main(void) {
       char srtype;
       int decision, i, num;
       struct element elem[MAX];
    
       do
       {
    	printf("\nThis program has the ability to do four tasks. "
    			"\n\nPlease pick the corresponding number related"
    			" to the task you wish to be done.\n\n"
    			"1. Sort elements stored on file by either name or abundance.\n"
    			"2. Find maxima from data on wavelengths and absorbances.\n"
    			"3. Root Finding\n"
    			"4. Element Database\n"
                            "5. Quit \n");
    
    	scanf("%i", &decision);
            i = getchar();  //pulls the newline off the input stream
    	if (decision == 1)
    	{
    	   printf("You have selected option 1\n");
               printf("Please Enter a Sort by Name or by Abundance [n/a] \n");
               scanf("%c", &srtype);
               i = getchar();
    	   num = abundance_sorter(elem);
               sortIt(elem, num, srtype);
               printIt(elem, num);
    	} 
    	if (decision == 2)
      	{
    	   printf("You have selected option 2");
    			
    	}
    	if (decision == 3)
    	{
    			printf("You have selected option 3");
    			
      		}
    		if (decision == 4)
    		{
    			printf("You have selected option 4");
    			element_info();
    			
      		}
    		else if(decision > 5)
    		{
    			printf("Invalid Number\n");
    		}
    		
    	}while(decision != 5);
    
       
       return 0;
    }
    /*
    That is the main file and this is abundance_sorter.h
    The code in comments is what has been tried yet proved detrimental to the program... ie,
     only outputting one line from the entire file etc.
    
    Code:
    */
    int abundance_sorter(struct element *elem)
    {
      FILE *infile;
    
      char line[100];
      char elements[20][50];
      char fname[30];
      int lcount, len, i;
     
      /* Read in the filename */
      printf("\nEnter the name the file you wish to open: ");
      fgets( fname, sizeof(fname), stdin );
      len = strlen(fname);
      fname[--len] = '\0';
      
      /* Open the file.  If NULL is returned there was an error */
      if((infile = fopen(fname, "rt")) == NULL) {
        printf("Error Opening File.\n");
        exit(1);
      }
    
      lcount = 0;
      while(fgets(line, sizeof(line), infile) != NULL) {
          /* Get each line from the infile */
          /* print the line number and data */
          printf("Line %d: %s", lcount, line);
          sscanf(line,"%s %s", elem[lcount].name, fname);
          elem[lcount++].abun = atof(fname);
      }
       i = getchar(); ++i;
       printf("\nFile reading finished");
      
      fclose(infile);  /* Close the file */
      return lcount; //    
    }
    void printIt(struct element *elem, int num) {
       int i;
    
       for(i = 0; i < num; i++) 
          printf("\n %d: %s %.2f", i+1, elem[i].name, elem[i].abun);
    }
    void sortIt(struct element *elem, int num, char srtype) {
    
       int i, j;
       for(i = 0; i < num - 1; i++) {
          for(j = i + 1; j < num; j++) {
             if(srtype == 'n') { //sort by name 
                if(strcmp(elem[i].name,  elem[j].name) > 0) {
                   swap(elem, i, j);
                }
             }
             else {  //a == sort by abundance
                if(elem[i].abun > elem[j].abun)
                   swap(elem, i, j);
             }
          }
       }
    }
    void swap(struct element *elem, int i, int j) {
       char tname[30] = { '\0' };
       double tabun;
    
       strcpy(tname, elem[i].name);
       tabun = elem[i].abun;
       strcpy(elem[i].name, elem[j].name);
       strcpy(elem[j].name, tname);
       elem[i].abun = elem[j].abun;
       elem[j].abun = tabun;
    
    }
    
    
    //ignore this! forces floating point linkage - don't call
    static void forcefloat(float *p)  
    {
        float f = *p;
        forcefloat(&f);
    }
    
    /*************** End of Program Touch Up ****************/
    //this is part 4, or element_info.h
    
    //Code:
    
    int element_info()
    {
    
    FILE *fp;
    char infofilename[127], repeat[9], element[127], symbol[127];
    int melt, answer;
    
       printf("\n\n[Please enter the filename:]\n\n");
    
          scanf("%s", infofilename);
          /* Try opening the file.*/
          fp = fopen(infofilename, "a"); /* If file exists, append data to end of file, else create new file...*/
          printf("Your file %s was created\n\n"
        		  "Now please enter the data you want stored"
        		  "\nElement: ", infofilename);
          scanf("%s", &element);
          fprintf(fp, "%s ", &element);
    
          printf("Symbol: ");
          scanf("%s", &symbol);
          fprintf(fp, "%s ", &symbol);
    
          printf("Melting Point: ");
          scanf("%d", &melt);
          fprintf(fp, "%d\n\n", melt);
    
          while(1)
          {
        	  printf("Would you like to enter more data?\n1. Yes\n2. No\n\n");
        	  scanf("%i", &answer);
        	  if(answer == 1)
        	  {
        	  printf("Please enter the data you want stored"
        	     		  "\nElement: ");
        	       scanf("%s", &element);
        	       fprintf(fp, "%s ", &element);
    
        	       printf("Symbol: ");
        	       scanf("%s", &symbol);
        	       fprintf(fp, "%s ", &symbol);
    
        	       printf("Melting Point: ");
        	       scanf("%d", &melt);
        	       fprintf(fp, "%d\n\n", melt);
        	       continue;
        	       }
        	  if(answer == 2)
        	  {
        		  printf("Thank you for exploiting me today");
        	  break;
        	  }
        	  else
        	  {
        		  printf("Invalid Number");
        		  continue;
        	  }
    
          }
    
          fclose(fp);
    
          return 0;
    }

  2. #17
    Registered User
    Join Date
    Feb 2009
    Posts
    21
    that's such a big help... thanks a lot.
    By looking at the code I think I am starting to understand how to use structs.

    Thanks again

  3. #18
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You're welcome Typhonius.

    In the swap function there's an error, though. See how tname[] is initiated over and over?

    Since it's never free()'d, it's a memory leak. Over time, it would cause the system to crash.

    The best fix is to initiate tname[] in the function that calls swap(), and then pass a pointer (the name of the array will do), to swap(). Then, just before leaving sortIt(), have the line of code: free (tname);

    That way it's just initiated once, and free'd just once.

    I didn't remove the other elements[][] array either, but it should be taken out since it's not used.

    And I thought I was up late!

    A slightly more polished version:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
                       //#include <math.h>
                       //#include <ctype.h>
                       //#include "abundance_sorter.h"
                       //#include "element_info.h"
    
    #define MAX 30
    
    
    //int decision;
    struct element {
      char name[40];
      double abun;
      //you can add wavelength or other data members here, easily. 
    };
    int abundance_sorter(struct element *);
    void printIt(struct element *elem, int);
    void sortIt(struct element *elem, int, char);
    void swap(struct element *elem, char *, int, int);
    
    static void forcefloat(float *p);  //ignore this!
    
    int main(void) {
       char srtype;
       int decision, i, num;
       struct element elem[MAX];
    
    	do
    	{
    	   printf("\nThis program has the ability to do four tasks. "
    			"\n\nPlease pick the corresponding number related"
    			" to the task you wish to be done.\n\n"
    			"1. Sort elements stored on file by either name or abundance.\n"
    			"2. Find maxima from data on wavelengths and absorbances.\n"
    			"3. Root Finding\n"
    			"4. Element Database\n"
                            "5. Quit \n");
    
    	   scanf("%i", &decision);
               i = getchar();  //pulls the newline off the input stream
    	   if (decision == 1)
    	   {
    	      printf("You have selected option 1\n");
                  printf("Please Enter a Sort by Name or by Abundance [n/a] \n");
                  scanf("%c", &srtype);
                  i = getchar();
    	      num = abundance_sorter(elem);
                  sortIt(elem, num, srtype);
                  printIt(elem, num);
    	   } 
    		if (decision == 2)
      		{
    			printf("You have selected option 2");
    			
    		}
    		if (decision == 3)
    		{
    			printf("You have selected option 3");
    			
      		}
    		if (decision == 4)
    		{
    			printf("You have selected option 4");
    			element_info();
    			
      		}
    		else if(decision > 5)
    		{
    			printf("Invalid Number\n");
    		}
    		
    	}while(decision != 5);
    
       ++i;
       return 0;
    }
    /*
    That is the main file and this is abundance_sorter.h
    The code in comments is what has been tried yet proved detrimental to the program... 
    ie, only outputting one line from the entire file etc.
    
    Code:
    */
    int abundance_sorter(struct element *elem)
    {
      FILE *infile;
      int lcount, len1, len2, i;
      char *line1, *fname;
      len2 = 45;
      line1 = calloc(len2, 1);
      fname = calloc(len2, 1);
      
     
      /* Read in the filename */
      printf("\nEnter the name the file you wish to open: ");
      fgets( fname, len2, stdin );
      len1 = strlen(fname) - 1;
      fname[len1]  = '\0';
      
      /* Open the file.  If NULL is returned there was an error */
      if((infile = fopen(fname, "rt")) == NULL) {
        printf("Error Opening File.\n");
        exit(1);
      }
    
      lcount = 0;
      while(fgets(line1, len2, infile) != NULL) {
         /* Get each line from the infile */
         /* print the line number and data */
    	  printf("Line %d: %s", lcount+1, line1);
    	  sscanf(line1,"%s %s", elem[lcount].name, fname);
         elem[lcount++].abun = atof(fname);
      }
      i = getchar(); ++i;
      printf("\nFile reading finished");
      
      fclose(infile);  /* Close the file */
      free(line1);
      free(fname);
      return lcount; //    
    }
    void printIt(struct element *elem, int num) {
       int i;
    
       for(i = 0; i < num; i++) 
          printf("\n %d: %s %.2f", i+1, elem[i].name, elem[i].abun);
    }
    void sortIt(struct element *elem, int num, char srtype) {
    
       int i, j;
       char *tname = calloc(45, sizeof(char)); 
    
       for(i = 0; i < num - 1; i++) {
          for(j = i + 1; j < num; j++) {
             if(srtype == 'n') { //sort by name 
                if(strcmp(elem[i].name,  elem[j].name) > 0) {
                   swap(elem, tname, i, j);
                }
             }
             else {  //a == sort by abundance
                if(elem[i].abun > elem[j].abun)
                   swap(elem, tname, i, j);
             }
          }
       }
       free(tname);
    }
    void swap(struct element *elem, char *tname, int i, int j) {
       
       double tabun;
    
       strcpy(tname, elem[i].name);
       tabun = elem[i].abun;
       strcpy(elem[i].name, elem[j].name);
       strcpy(elem[j].name, tname);
       elem[i].abun = elem[j].abun;
       elem[j].abun = tabun;
    
    }
    
    
    //ignore this! forces floating point linkage - don't call
    static void forcefloat(float *p)  
    {
        float f = *p;
        forcefloat(&f);
    }
    
    /*************** End of Program Touch Up ****************/
    //this is part 4, or element_info.h
    
    //Code:
    
    int element_info()
    {
    
    FILE *fp;
    char infofilename[127], repeat[9], element[127], symbol[127];
    int melt, answer;
    
       printf("\n\n[Please enter the filename:]\n\n");
    
          scanf("%s", infofilename);
          /* Try opening the file.*/
          fp = fopen(infofilename, "a"); /* If file exists, append data to end of file, else create new file...*/
          printf("Your file %s was created\n\n"
        		  "Now please enter the data you want stored"
        		  "\nElement: ", infofilename);
          scanf("%s", &element);
          fprintf(fp, "%s ", &element);
    
          printf("Symbol: ");
          scanf("%s", &symbol);
          fprintf(fp, "%s ", &symbol);
    
          printf("Melting Point: ");
          scanf("%d", &melt);
          fprintf(fp, "%d\n\n", melt);
    
          while(1)
          {
        	  printf("Would you like to enter more data?\n1. Yes\n2. No\n\n");
        	  scanf("%i", &answer);
        	  if(answer == 1)
        	  {
        	  printf("Please enter the data you want stored"
        	     		  "\nElement: ");
        	       scanf("%s", &element);
        	       fprintf(fp, "%s ", &element);
    
        	       printf("Symbol: ");
        	       scanf("%s", &symbol);
        	       fprintf(fp, "%s ", &symbol);
    
        	       printf("Melting Point: ");
        	       scanf("%d", &melt);
        	       fprintf(fp, "%d\n\n", melt);
        	       continue;
        	       }
        	  if(answer == 2)
        	  {
        		  printf("Thank you for exploiting me today");
        	  break;
        	  }
        	  else
        	  {
        		  printf("Invalid Number");
        		  continue;
        	  }
    
          }
    
          fclose(fp);
          return 0;
    }
    Last edited by Adak; 02-08-2009 at 12:38 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pick data from file store in array
    By swgh in forum C Programming
    Replies: 1
    Last Post: 07-10-2009, 09:57 AM
  2. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  3. Dynamic Array substitution in composite data variable
    By DavidDobson in forum C Programming
    Replies: 2
    Last Post: 08-12-2008, 04:29 AM
  4. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  5. Template Array Class
    By hpy_gilmore8 in forum C++ Programming
    Replies: 15
    Last Post: 04-11-2004, 11:15 PM