Error when reading from text into double array

Greetings all.
I have a text file named data.txt . data.txt contains "double" numbers, one in each line. My attempt is to:
1. check how many lines are in data.txt
2. declare a double array of proper size
3. copy data from txt file line by line into that array

But when I print the array out it results in erroneous small random numbers, instead of those from data.txt. Here is my code:

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>

#include <fstream>
#include <istream>

using namespace std;

int main()
{
    cout << "Hello world!" << endl << endl;

    int number_of_lines = 0;
    string line;
    ifstream myfile("data.txt");

    while (getline(myfile, line))
	{
        ++number_of_lines;
	}

    cout << "Number of lines in text file: " << number_of_lines << endl << endl;

    int i = 0;
    double a;

    double data[number_of_lines];

    while(myfile >> a)
    {
    data[i] = a; 
    i++;
    }

	for (int b = 0; b < number_of_lines; b++)
    {
        cout << data[b]<<endl;
    }

    return 0;
}


What did I do wrong ? I am just beginning to use file streaming. Help is much appreciated, thank you.
Kind regards, t
Last edited on
I thnk its because myfile is already in the last line after line countng, try to use this www.cplusplus.com/reference/istream/istream/seekg/
Thank you for your answer. You are right, this was the error. But I can't manage to modify code from the example you linked to work for my case. in these lines :

is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);

the "length" is much too big, it probably reads single characters. The initial code that I have posted works fine for giving the right number for "number_of_lines", but storing in array doesn't function.
I would like the full number in a line to be read as a whole and placed in an array.
Do you know what function I could use for this ? Thank you.
Last edited on
How about close and reopen the file ?
Thank you, that was it. I didn't know about opening and closing files until checking here:
http://www.cplusplus.com/reference/fstream/fstream/close/
Topic archived. No new replies allowed.