reading in arrays with fscanf

Started by
4 comments, last by DevFred 15 years, 4 months ago
Hello, I'm having a really basic issue with fscanf but I'm not a very good programmer in that I don't really know the fundamentals of C++. Basically I have a File that is a few hundred lines long and each line has the format "long bool 32bithex" so I have 3 arrays, one to store the data from each of these 3 columns. The code snippet is as follows (the file is open):

long times0[1000];
long addr0[1000];
bool rw0[1000];
FILE *f0;

for(int i=0;i<100;i++)
{
     fscanf(f0, "%li %b %lx", &times0, &rw0, &addr0);
     printf("TIMES:  %i %li\n", i, times0);
}
However, using this code, all 3 columns get read into the times0 array! times0[0] has the right value, but times0[1] somehow has what rw0[0] should have had and times0[2] has what addr0[0] should have had! What am I doing wrong here? Edit: Alternatively, if my code is just acting wacky and is beyond repair, could someone suggest how to do what I want to do properly? [Edited by - innocuous on December 4, 2008 3:22:19 AM]
Advertisement
print the return value of fscanf, it tells you how many arguments were scanned successfully.

Show us some example lines from your file.
Thanks for the reply. The file reads as follows:

183 0 0x00000010269 1 0x094055b0346 1 0x094055a8361 1 0x094055ac

...and so on. When I save the return value of fscanf to a variable and output it, it appears as if fscanf is only scanning 1 value at a time although I am telling it to scan 3. I used the code

int temp = fscanf(f0, "%li %b %lx", &times0, &rw0, &addr0);printf("ADDR:  %i %li %i\n", i, times0, temp);


The result looks like:

ADDR:  0 183 1ADDR:  1 0 1ADDR:  2 16 1ADDR:  3 269 1ADDR:  4 1 1

... and so on. It's definitely only scanning one variable at a time, but I don't know how to make it scan more than one now as I thought the code I used was correct.
As far as I can tell, the format string %b does not exist. This is no surprise because you are using the C function scanf, and there is no boolean data type in C. Try reading into a temporary int and then assign that int to the bool in the array. Or use proper C++ I/O.
That was 100% the problem, I have no idea where I got the idea that there was a binary read in format. Thanks, I wouldn't have caught that for awhile!
That's why we prefer typesafe C++ solutions.

This topic is closed to new replies.

Advertisement