ifstream problem

B

Bernhard Hidding

Hi there,
I want to read an ASCII file ("magnetfile.dat") consisting of doubles into
an array. The ASCII file looks like this:

1.0 1.0 1.0 0.5
2.0 1.0 1.0 0.4
usw.

My code:

double magnefield[200]; //this is the array
int i;

ifstream magnetic_field_array;
magnetic_field_array.open("magnetfile.dat");
for (i=0;i<20;i++)
{
magnetic_field_array >> magnefield; //should write 1.0 , 1.0, 1.0,
0.5 ... into the array
}
magnetic_field_array.close();

I use g++ on SuSE 9.1. The executable runs, however, when I print out my
array magnefield, strange numbers appear. What is going wrong?
By the way: my file "magnetfile.dat" is in my working directory. However,
g++ does not give our an error message if I remove the file, so I am not
sure if the program finds the file after all. Might this be the problem?

Thanks for your help,
Bernhard
 
J

John Harrison

Bernhard Hidding said:
Hi there,
I want to read an ASCII file ("magnetfile.dat") consisting of doubles into
an array. The ASCII file looks like this:

1.0 1.0 1.0 0.5
2.0 1.0 1.0 0.4
usw.

My code:

double magnefield[200]; //this is the array
int i;

ifstream magnetic_field_array;
magnetic_field_array.open("magnetfile.dat");
for (i=0;i<20;i++)
{
magnetic_field_array >> magnefield; //should write 1.0 , 1.0, 1.0,
0.5 ... into the array
}
magnetic_field_array.close();

I use g++ on SuSE 9.1. The executable runs, however, when I print out my
array magnefield, strange numbers appear. What is going wrong?
By the way: my file "magnetfile.dat" is in my working directory. However,
g++ does not give our an error message if I remove the file, so I am not
sure if the program finds the file after all. Might this be the problem?


It probably is. You should test to see if you open the file successfully.

ifstream magnetic_field_array("magnetfile.dat");
if (!magnetic_field_array.is_open())
cerr << "could not open file\n";

It is your responsibility to print an error message if you cannot open a
file, not the compilers.

john
 

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

Similar Threads


Members online

Forum statistics

Threads
474,183
Messages
2,570,968
Members
47,524
Latest member
ecomwebdesign

Latest Threads

Top