How to read numercial data from a file

W

Wei-Chao Hsu

There are some data files look like

1.) data1.txt
----------------
1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0
10.0

2.) data2.txt
---------------------
1.0 2.0 3.0 4.0
5.0 6.0 7.0 8.0
9.0 10.0

3.) data3.txt
----------------
1.0 2.0
3.0 4.0 5.0
6.0 7.0
8.0 9.0 10.0

They will be store in a array. A[0]=1.0,A[1]=2.0,.....
I never know the format in each file.
In fortran, I just declare an array A(10), and read them
READ(file_no,*)A
I don't know how to do the same thing in C.
I need your help. Thanks!

Dennis
 
J

John Harrison

There are some data files look like

1.) data1.txt
----------------
1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0
10.0

2.) data2.txt
---------------------
1.0 2.0 3.0 4.0
5.0 6.0 7.0 8.0
9.0 10.0

3.) data3.txt
----------------
1.0 2.0
3.0 4.0 5.0
6.0 7.0
8.0 9.0 10.0

They will be store in a array. A[0]=1.0,A[1]=2.0,.....
I never know the format in each file.
In fortran, I just declare an array A(10), and read them
READ(file_no,*)A
I don't know how to do the same thing in C.
I need your help. Thanks!

Dennis
Well its not so difficult in C++ (I assume you mean C++ not C, since you
posted to a C++ group), You just declare the array and read them. The only
difference is that you must read in some sort of loop.

#include <fstream>

std::ifstream file("data1.txt");
double a[10];
for (int i = 0; i < 10; ++i)
file >> a;

If you want a C answer post to
john
 
T

Thomas Matthews

John said:
There are some data files look like

1.) data1.txt
----------------
1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0
10.0
[snip]
Well its not so difficult in C++ (I assume you mean C++ not C, since
you posted to a C++ group), You just declare the array and read them.
The only difference is that you must read in some sort of loop.

#include <fstream>

std::ifstream file("data1.txt");
double a[10];
for (int i = 0; i < 10; ++i)
file >> a;

If you want a C answer post to
john


Actually, he did. Perhaps, I didn't pay attention
to the time and date stamps of these posts. ;-)


--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top