www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1999/10/26/07:00:39

From: "Paulu van Zijl" <paulu AT proloan DOT co DOT za>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Help to read array from text file
Date: Tue, 26 Oct 1999 10:09:10 +0200
Organization: The South African Internet Exchange
Lines: 73
Message-ID: <7v3npp$opl$1@ctb-nnrp2.saix.net>
References: <7p2s92$6b95e$2 AT titan DOT xtra DOT co DOT nz>
NNTP-Posting-Host: 196.25.225.24
X-Trace: ctb-nnrp2.saix.net 940925561 25397 196.25.225.24 (26 Oct 1999 08:12:41 GMT)
X-Complaints-To: abuse AT saix DOT net
NNTP-Posting-Date: 26 Oct 1999 08:12:41 GMT
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 5.00.2014.211
X-MimeOLE: Produced By Microsoft MimeOLE V5.00.2014.211
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

Steve <malex AT xtra DOT co DOT nz> wrote in message
news:7p2s92$6b95e$2 AT titan DOT xtra DOT co DOT nz...
> Well,
>
> I am trying to read a text file which contains 5 rows and 5 columns of
> numbers into an array, then print out the array on screem in the same
format
> that is was in the text file so that individual parts of the array can be
> summed, counted etc. so far, I have not been able to do so, any help with
> this would be very welcome.
>
> Included is what I have come up with so far, yer ok, so I am also new to
> this, there could be obvious mistakes in there of which I cannot see.
Below
> is the file that I have been working on.
>
> Steve
>
> #include <stdio.h>
> #include <stdlib.h>
>
> main()
> {
>     FILE * aa;
>     char fname[81], t[5][5];
>
>      int a, ch, team, last;
>
>     printf("Enter name of file to read: ");
>     scanf("%80s", fname);
>
>     aa = fopen(fname, "r");
>     if (aa == NULL) {
>
>         fprintf(stderr, "File cannot be opened.\n");
>         exit(1);
>         }
>
>      while ((ch = getc(aa)) >= 0) {   /* while not EOF */
>      for (a = 0; a <= 26; ++a)
>      fscanf(stderr, "%s", t[a]);
You cannot use %s here, because you're reading int's not strings.  Also you
must use aa in the place of stderr, because aa is the file stream you're
reading from.
>
>      fprintf(stderr, "%s     \n", t[a]);
>      }

Firstly, you cannot use t[a], because you defined t as t[5][5];.  Also char
t[5][5] should read int t[5][5], because you are going to read int's into
the array, not chars.

Then I would write the while loop as two for loops, as follows:

int i, j, done;

done = 1;  /*make sure that done doesn't equal EOF otherwise the 2 for loops
would never execute!*/

for (i = 0; (i < 5) && (done != EOF); i++)
  for (j = 0; (j < 5) && (done != EOF); j++)
  {
      done = fscanf(aa, "%d", t[i][j]);
      fprintf(stderr, "%d\n", t[i][j]);
  }
>
>      fclose(aa);
>      return 0;
> }
>
>


- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019