Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Writing the contents of a text file into an array

Status
Not open for further replies.

DMcCleary

Technical User
May 8, 2002
1
US
Hi, I seem to be having trouble doing this.
I have a text file containing: 173 44 84 0 25
and when I read in the numbers and try to spit them back out, I get: -1.00 -1.00 -1.00 -1.00 -1.00

Here's the code.

int main()
{

/* define local variables */
FILE *firstfile;
float NumArray[5];
int count;

/* begin statements */

/* opens the file A:\Five_Num.txt */
firstfile = fopen("A:\Five_Num.txt", "r");

/* reads in numbers from file */
for(count = 0; count < 5; count++)
NumArray[count] = fscanf(firstfile, &quot;%f&quot;, &NumArray[count]);

for(count = 0; count < 5; count++)
printf(&quot;%.2f&quot;, NumArray[count]);

fflush(stdin);
getchar();
return(0);
}

So what's my problem?
 
In the instruction:

Code:
NumArray[count] = fscanf(firstfile, &quot;%f&quot;, &NumArray[count]);

you read the numbers from the file into
Code:
NumArray[count]
like you want to, but then you assign the result of the fscanf to
Code:
NumArray[count]
. Since fscanf returns the number of arguments it read, you keep getting 1. Just take out
Code:
NumArray[count] =
and it should work better.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top