Reading and sum data from a textfile with multiple numerical columns

lebron letchev
lebron letchev used Ask the Experts™
Dear all,

Using Turbo Pascal or C or Turbo C (well primitive), how I read several columns with numbers from a text file and give the sum of each one?

Thank you in advance (if I found anyone that have programmed in Pascal.
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Fabrice LambertConsulting
Distinguished Expert 2017


Not many solutions here, you'll have to read your file line by line, split each line, load everything in a 2D array (or a linearised array)
Then browse your array column by column to perform the sums.
Top Expert 2016
the following ansi c code should do the job if the text file contains only numbers.

turbo c is pretty old but should compile as well.

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#define MAXCOLS 4
#define MAXROWS 1000

int main () 
   FILE * fp = 0;
   char buf[1024] = { 0 };   // use buffer big enough for any text line
   double data[MAXCOLS][MAXROWS] = { 0 };   // assume 4 columns and max 1000 rows
   double sums[MAXCOLS] = { 0 };
   int nrow = 0;
   int ncol = 0;  

   fp = fopen ("file.txt", "r");
   if (fp == 0)
           return errno;
   while (fgets(buf, 1024, fp) == buf)
         int len = strlen(buf);
         char * p = buf;
         char * pend = 0;
         for (ncol = 0; ncol < MAXCOLS; ++ncol)
             pend = 0;
             data[ncol][nrow] = strtod(p, &pend);
             sums[ncol] += data[ncol][nrow];
             if (pend == 0 || *pend == '\0')   // either no end or end is end-of-line
                    break;   // no more numbers ==> next row
             p = pend++;  // one char after end of previous number
         if (++nrow >= MAXROWS)
   printf("%d rows read\n", nrow);
   for (ncol = 0; ncol < MAXCOLS; ++ncol)
        printf("  sum[%d] = %9.2f\n", ncol, sums[ncol]);
   return 0;

Open in new window



Many thanks


Many thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial