Peanut
Peanut

Reputation: 33

Reading from dat file into an array

I'm a first year student and im busy with a coding exercise but cant seem to crack the case.

when reading from number.dat which is 20 random numbers, i get them read into the array and I print them just for diagnostics at this stage but my print of the data in the array is completely messed up.

Any help is much appreciated.

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main()
{
    ifstream in_stream;
    ofstream out_stream;

    int array_size = 20;
    int position = 0;
    double numbers[array_size];

    //Check input and output file.
    in_stream.open("Number.dat");
    if (in_stream.fail())
    {
        cout << "Input file opening failed";
        exit(1);
    }

    //array to read data from array as long as we dont reach the end of file marker
    while(! in_stream.eof() && position < array_size)
    {
        in_stream >> numbers[position];
        position++;
        cout << position << " = "
             << numbers[position] << endl;
    }

}

Upvotes: 1

Views: 4743

Answers (3)

Peanut
Peanut

Reputation: 33

as per the answers above , my issue was that i was incrementing my loop variable before printing, so it tried to print the next value in the array.

Thank you all for helping

while(! in_stream.eof() && position < array_size)
{
    in_stream >> numbers[position];
    cout << position << " = "
         << numbers[position] << endl;
    position++;
}

Upvotes: 1

Mo H.
Mo H.

Reputation: 1818

You are reading parts of your array that haven't been filled yet, so you should be getting junk, try this:

    while(! in_stream.eof() && position < array_size)
    {
        in_stream >> numbers[position];
        cout << position << " = "
             << numbers[position] << endl;
        position++;
    }

Upvotes: 1

molbdnilo
molbdnilo

Reputation: 66371

There are two problems, one that's not the cause of this particular problem.

First, using while (!instream.eof()will cause you to read one time too many, because eof() doesn't become true until after the first attempted read after the last successful one.

But the immediate cause is that you're incrementing position between the reading and the printing, so you're printing a value that hasn't been set yet.

Try this:

while (position < array_size && in_stream >> numbers[position])
{
    cout << position << " = "
         << numbers[position] << endl;
    position++;
}

Upvotes: 5

Related Questions