ifstream problem

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bernhard Hidding

    ifstream problem

    Hi there,
    I want to read an ASCII file ("magnetfile.da t") 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("mag netfile.dat");
    for (i=0;i<20;i++)
    {
    magnetic_field_ array >> magnefield[i]; //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



  • John Harrison

    #2
    Re: ifstream problem


    "Bernhard Hidding" <hidding@uni-duesseldorf.de> wrote in message
    news:cn03qd$mea $1@news1.rz.uni-duesseldorf.de. ..[color=blue]
    > Hi there,
    > I want to read an ASCII file ("magnetfile.da t") 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("mag netfile.dat");
    > for (i=0;i<20;i++)
    > {
    > magnetic_field_ array >> magnefield[i]; //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?[/color]

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

    ifstream magnetic_field_ array("magnetfi le.dat");
    if (!magnetic_fiel d_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


    Comment

    Working...