Think in terms of rows of records consisting of fields instead of rows and columns:
in = fopen ( "data1.txt", "r" );
if ( in == NULL ) {
/* Error */
} else {
int i, j;
do {
fscanf ( in, "%s", dummy );
if ( strcmp ( dummy, "ZZZZZ" ) == 0 )
break;
/* Fill the ith record */
strcpy ( place[i], dummy );
for ( j = 0; j < max_cols; j++ )
fscanf ( in, "%f", &rain[i] );
/* Display the ith record */
printf ( "%10s\t", place[i] );
for ( j = 0; j < max_cols; j++ )
printf ( "%2.2f", rain[i] );
printf ( "\n" );
} while ( i < max_rows );
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>First thing I saw was you mixed a little basic with C.
You're gonna love this. :) In C, since the 95 ammendment, the header defines macros such as and, or, and not_eq as a reasonable alternative to the nasty trigraphs for implementations that don't support the requisite characters to represent the base language. In standard C++ all of those macros are language keywords. So it's not quite a stretch to imagine C or C++ code using them. ;)
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Your nested for loops mean that you are trying to read 144 values each line. To me it looks like the do...while is attempting to be what the first for loop should be: rows. I'd do something more like this.
for ( int i = 0; i < maxrows; ++i )
{
fscanf ( fp,"%s", place[i] );
if ( strcmp ( place[i], "ZZZZZ" ) == 0 )
{
break;
}
printf ( "%10s", place[i] );
annual = 0;
for ( int j = 0; j < maxcols; ++j )
{
fscanf ( fp, "%f", &rain[i][j] );
printf ( "\t%2.2f", rain[i][j] );
annual = annual + rain[i][j];
}
printf("\tAnnual rainfall is %3.2f\n", annual);
}
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
Unless the format of your file has changed, you're trying to read too many floats, and fscanf is failing miserably when you get to the next city. Here's how any logic you use should work:
for each line
read the name
read 12 floats
Anything else will give you incorrect output. As it is, your code is trying to do this:
for each line
read the name
read 144 floats
Notice the difference?
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401