I need to display an array of structures on screen of an unknown length

J

James

Hello,
We've been given a program that reads data from a .dat file. It looks
something like this:

1 1.0 1.2
2 2.4 3.5
3 3.4 6.5
4 3.3 2.2

....and so on. I need to know a way of preinting this on screen - i can
do this easily for a file of known size, i have a statement like:

fprintf(stdout, "%d %lf %lf", node_array[no_nodes-1].id,
node_array[no_nodes-1].x, node_array[no_nodes-1].y);

where i can replace the "-1" with "-n". However, seeing as the arrays
are of a length anywhere between 1 and 100 lines long, well, theres
got to be a better way of doing it! Otherwise, any array less than 100
structures long will have a lot of rubbish printed out. Oh course you
knew that - I'm very new at C, so I'm being obvious for my own
understanding!

Any help would be very much appreciated!

James Brennan - Craddock
 
P

Pushkar Pradhan

1. I assume you're allocating memory for 100 elements as that's the max
you're expecting.

2. You can check if there are no more elements by reading like this:
while(fscanf("%d %lf %lf", &id, &x, &y) != EOF)
fprintf(....)

If the end of file is reached the while loop exits.
 
I

Irrwahn Grausewitz

Hello,
We've been given a program that reads data from a .dat file. It looks
something like this:

1 1.0 1.2
2 2.4 3.5
3 3.4 6.5
4 3.3 2.2

...and so on. I need to know a way of preinting this on screen - i can
do this easily for a file of known size, i have a statement like:

fprintf(stdout, "%d %lf %lf", node_array[no_nodes-1].id,
node_array[no_nodes-1].x, node_array[no_nodes-1].y);

where i can replace the "-1" with "-n". However, seeing as the arrays
are of a length anywhere between 1 and 100 lines long, well, theres
got to be a better way of doing it! Otherwise, any array less than 100
structures long will have a lot of rubbish printed out. Oh course you
knew that - I'm very new at C, so I'm being obvious for my own
understanding!

Any help would be very much appreciated!

Two possible approaches spring to mind:

1. Count the number of records/lines when you read them in, so
you know how many to print afterwards.

2. Use a sentinel, i.e an indicator value that tells you when
no more valid data follows.

HTH a bit.

Regards
 
K

Kevin Goodsell

Pushkar Pradhan wrote:

<top-post snipped>

This is the second time you've been asked. Please stop top-posting.

-Kevin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top