Text file into Array

Hi

If I have a text file containing data of one number per line such as:
1
2
3
4
5

How do i read in this data if the total number of lines is unspecified but does not exceed 100 lines?

I am wanting to use an array but how would I do this?
Don't want to use vectors.
Last edited on
1
2
3
4
5
int data[100];
int index = 0;
while(input >> data[index++])
{}
//Other code. index now stores amoun of elements in array. 
I tried the follwing however it does not work. It displays random numbers instead of the numbers in the textfile.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream infile("data.txt");
    if (!infile)
    {
        cout << "Unable to open file" << endl;
        return -1;
    }

    double myArray[100];
    int index = 0;
    while(infile >> myArray[index++])
    {
        cout << myArray[index] << endl;
    }
    return 0;
}
Last edited on
Because you are outputing values just after the last read everytime.

while(infile >> myArray[index++]) will read number into myArray[index] and increase index afterward. (e.g. read value into myArray[3] and increase index to 4)
Then you are trying to read tan one-past the end value.

Move output to another loop.
If i change the while loop and make it index instead of index++ it outputs all the values correctly. Howcome, since I did not increment the index anywhere?
Because you just overwriting first element over and over so old data are getting deleted.
If I had 5 values from 1 to 5 in a column in a text file. How would I square all values and add them which equals 55 and then divide by the total number of values being 5. Therefore the answer would be 11.
1
2
3
4
5
6
7
8
int value;
int sum = 0;
int count = 0;
while(input >> value) {
    sum += value*value;
    ++count;
}
int result = sum / count;
Last edited on
Thanks
Topic archived. No new replies allowed.