Joe Doe Joe Doe - 2 months ago 15
C++ Question

How to read integers from a text file and store them in an array?

I have a file named example.txt with 7 integers formatted as such,


1

2

3

4

5

6

7


My code is,

#include<iostream>
#include<fstream>

using namespace std;

int main() {

int arr[7];

ifstream File;
File.open("example.txt");

int n = 0;
while (File >> arr[n]) {
n++;
}
File.close();

for (int i = 0; i < 7; i++) {
cout << arr[i] << endl;
}

return 0;
}


This code works, because I already know how many integers are in the text file. What should I change in the code to make sure it works if I don't know how many integers are in the file? In other words, if someone were to change the number of integers in the text file, how do I make sure my code works?

Answer

you were almost C++ compliant there.

So I took the time to change a few lines of your code replacing the C-style array by a vector. That was the only thing missing to make it really C-free :). See the **** comments when I changed stuff.

Use vector everytime, specially when you don't know the size of the list (and even if you know the size since you can reserve or resize or create the vector with the proper dimension at start.

#include<iostream>
#include<fstream>
#include<vector>   // ****

using namespace std;

int main() {

vector<int> arr;   // ****

ifstream File;
File.open("example.txt");

int n;                     // ****
while (File >> n) {        // ****
    arr.push_back(n);      // ****
}
File.close();

for (auto n : arr) {      // ****
    cout << n << endl;    // ****
}

return 0;
}

Use -std=c++11 flag to compile it.

Comments