Read from file of arbitrary length

I have a .txt file containing 100 integers all on one line, each integer separated by a space. This is the code I have made to read this file and print the integers from it

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
#include <fstream>
#include<iostream>
int main(){
    
std::ifstream myFile;

myFile.open("sample.txt");
float filecontents[100];

int i=0;
if(myFile.is_open())
{
   while(!myFile.eof())
   {
      myFile >> filecontents[i];
      std::cout<<filecontents[i]<<std::endl;
      i++;
   }
}

myFile.close();

system("pause");
}


What I am now trying to do is to generalise this code to read from files of arbitrary length. I am thinking I need to count the elements in the file then use that number to set the size of the array filecontents[]. Not sure though, any advice welcome.
just put your values in a container, if you need those values to persist
(and while you're at it, stop trying to use eof() as a while loop condition)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <fstream>
#include <iostream>
#include <vector>

int main(){

    std::ifstream myFile("sample.txt");
    std::vector<float> filecontents;

    float value;
    while(myFile >> value)
    {
        filecontents.push_back(value);
        std::cout << filecontents.back() << '\n';
    }
}


Incidentally, if the file really has "100 integers", std::vector<int> is even more sensible
Last edited on
Topic archived. No new replies allowed.