Reading in .dat file, line by line, and storing in int array

I have a .dat file with numbers on each line. For example...

345
66478
43
60263
5212
8943346
...etc

I want to read in each line, one by one, and store each line into an index of an int array.

How would I do that? Also, would I first have to read through the file to see how many lines of numbers there are, and then set the array to that size?

I've been looking it up and it seems like there are so many ways to do this. Which one is the best for what I'm trying to do?

Basically this is what I have so far...

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

using namespace std;

int main()
{
        ifstream inputFile;
	inputFile.open("testfile.dat");
	if(!inputFile.is_open())
        {
            exit(EXIT_FAILURE);
        }
	inputFile.close();
	system ("pause");
}
Last edited on
The most flexible way is to use a vector. If you've no idea how many values are in the file, this will dynamically adjust as required.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>
#include <vector>

    using namespace std;

int main()
{    
    ifstream fin("testfile.dat");
    int num;
    vector<int> vec;
    
    while (fin >> num)
        vec.push_back(num);

    cout << "count = " << vec.size() << endl;
    cout << "first = " << vec[0] << endl;
    cout << "last  = " << vec[vec.size() -1] << endl;
    
    return 0;
}


Awesome. Works perfect. Thank you!

Do I need to close the file when I'm done with it?
There's one problem with it. When I try to get it to cout all the numbers, it starts out fine, then stops half way through and can't complete 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
26
27
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <vector>

using namespace std;

int main()
{

    ifstream fin("testfile.dat");
    int num;
    vector<int> vec;

    while (fin >> num)
    {
        vec.push_back(num);
    }

    for(int i = 0; i <= vec[vec.size()-1];i++)
    {
        cout << vec[i] << endl;
    }

    system ("pause");

}
Last edited on
Well, the file will be automatically closed, in this case when the program ends. In general, when the fstream goes out of scope, the file is closed.

Personally I've always been in the habit of closing files when I'm done, (it's usually required in various other programming languages) but since C++ streams will do it for you, it's mostly not necessary, except perhaps in specific circumstances. An example might be when you want to output some data to a file, close it and then re-open it as an input file etc.
Nevermind, I got it. It should be vec.size -1, not vec[vec.size-1]
A minor comment. Instead of i <= vec.size() - 1
you could put i < vec.size()
It means the same, but a bit easier to read.
Thanks! You really helped a lot.
Topic archived. No new replies allowed.