read numbers from a file

This is a discussion on read numbers from a file within the C Programming forums, part of the General Programming Boards category; hello, i am new to c programming and i have just begun some basic work. i am trying to read ...

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    3

    read numbers from a file

    hello,

    i am new to c programming and i have just begun some basic work. i am trying to read three numbers from a line, that's separated by a space like, "11 32 43", in a separate text file and i am trying to read each number and get the sum to print. unfortunatley i'm not too sure about how to go about reading the numbers... here's a snippet...

    Code:
      int linenum = 0;   // counting from 1
      char *ch;     // store each input character here
      int num;
      
      while( ( *ch = getchar() ) != EOF )
      {
             if ( !( (*ch == 32) || (*ch == '\n') ) )
             {
                num = atoi(ch);
                printf("%d" , num);
             }    
      }
    i'm afraid that using the "getchar()" will not work with double digit numbers. i was just wondering what is the best way to go about reading the numbers, per line. i get the corresponding ascii number, but i need to change that to an integer value, for calculation.

    thank you.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    181
    hope you are expecting some like this

    Code:
    #include<stdio.h>
    
    int main()
    {
            char c;
            int sum=0;
            FILE *fp;
            
            if((fp=fopen("test.txt","r"))==NULL)
            {
                    printf("cannot open the file");
                    exit(1);
        }
        else{
        do
        {
            c=fgetc(fp);
            if(c==' ' || c=='\n')
            continue;
            printf("%c",c);
        }while(c!=EOF);    
    }
    getchar();
    }
    hope this will help u out,

    s.s.harish

  3. #3
    Registered User
    Join Date
    Mar 2005
    Posts
    3
    i took a look around, and then wrote this snippet of code... can anyone give me advice if this is the best possible way to do this? or if there are any other ways to count the 3 numbers (i.e. "1 55 21"), add them up for a text 30 lines deep?

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main(void)
    {
      FILE *fp;
      int array1[3];
      int linect = 1;
      int linesum = 0;
      char buf[128];
    
      fp = fopen("numbers.txt", "r");
      
      if(fp == NULL)
      {
        puts("Cannot open file for reading");
        exit(EXIT_FAILURE);
      }
    
      while( linect < 31 )  
        {
        fgets(buf, sizeof(buf), fp);
        sscanf(buf, "%d %d %d", &array1[0], &array1[1], &array1[2]);
        printf("Set %d - 1st: %d, 2nd: %d, 3rd: %d", linect, array1[0], array1[1], array1[2]);
        linesum = (array1[0] + array1[1] + array1[2]);
        printf(" Line Sum = %d \n", linesum);
        linect++;
        }
    
      fclose(fp);
      
      int a;
      scanf("%d", &a);
    
      return 0;
    }
    thanks!

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    181
    >i took a look around, and then wrote this snippet of code... can anyone give me advice if this is the best possible way to do this? or if there are any other ways to count the 3 numbers (i.e. "1 55 21"), add them up for a text 30 lines deep?

    by looking at your code your are more complicating the things there

    i think u dont need the array to store the numbers untill u need those values for the future use in the program. look at this code:

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    int main()
    {
            char c;
            int sum=0, temp;
            FILE *fp;
            
            if((fp=fopen("test.txt","r"))==NULL)
            {
                    printf("cannot open the file");
                    exit(1);
        }
        else{
        while((c=fgetc(fp))!=EOF)
        {
               if(c==' ' || c=='\n')
            continue;
            printf("%c",c);
            temp= c - '0';
    
            //printf("%d\n",temp);
            sum=sum+temp;
        
        }
        printf("\nThe sum of three number is %d\n", sum);
    }    
    fclose(fp);
    getchar();
    return 0;
    }
    here i am not storing the values int an array. i am printing sum value when it comes out of the loop.

    s.s.harish

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    The problem with your example is that it doesnt handle numbers that are more than one digit. Read the origional post again and you'll see the following numeric sequence:
    "11 32 43"
    Your example would give:

    1 + 1 + 3 + 2 + 4 + 3 = 14

    It should give:

    11 + 32 + 43 = 86

    Unless my math is wrong. Then blame it on being tired.

    Perhaps a look at this FAQ entry will give you some insight on how to get numbers in general.

    Quzah.
    Hope is the first step on the road to disappointment.

  6. #6
    Registered User
    Join Date
    Apr 2004
    Posts
    173
    Haroonie, the way you are reading the text forces the program to keep reading when they are no more inputs thus it would simply use the previous fgets() result since you are not using the value of fgets() to terminate the loop once an EOF occurs. So something like this should suffice:

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main(void)
    {
      	FILE *fp;
      	int array1[3];
      	int linect = 0;
      	int linesum = 0;
      	char buf[128];
    
      	fp = fopen("numbers.txt", "r");
      
      	if(fp == NULL)
      	{
        		fprintf(stderr,"Cannot open file for reading");
     	   	exit(EXIT_FAILURE);
      	}
    
     	 while( fgets(buf,sizeof(buf),fp) != NULL )  
     	 {
    		sscanf(buf, "%d %d %d", &array1[0], &array1[1], &array1[2]);
     	   	printf("Set %d - 1st: %d, 2nd: %d, 3rd: %d", linect, array1[0], array1[1], array1[2]);
      	  	linesum = (array1[0] + array1[1] + array1[2]);
     	   	printf(" Line Sum = %d \n", linesum);
     	   	linect++;
    	 }
    	
     	 if(fclose(fp) != 0)
    	 {
    		fprintf(stderr,"Could not close file properly!\n");
    		exit(EXIT_FAILURE);
     	 }
    
     	 return 0;
    }
    You should also check the fclose() return value, and I've also taken out your last few lines for input - run the program in a terminal so you don't need those lines. Otherwise just add it in like you did before.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  2. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. archive format
    By Nor in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 08-05-2003, 07:01 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21