Search code examples
c++fileifstream

Read integer data from a file


I am just getting started on C++ and am working on codeval questions, so if anyones done that, they'll recognize this problem as it's the first on the list. I need to open a file that has 3 columns of space separated integer values. Here is mine, under fizbuz.txt. I need to get the integer values from the file and store them for later use elsewhere in the program.

1 2 10
3 5 15
4 5 20
2 8 12
2 4 10
3 6 18
2 3 11
8 9 10
2 5 8
4 9 25

Now I can open the file just fine, and I've used getline() to read the files just fine using my below code. However, I don't want them in string format, I'd like them as integers. So I looked around and everyone basically says the same notation (file>>int1>>int2...). I've written some code exactly how I've seen it in a few examples, and it does not behave at all like they're telling me it should.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    string filename = "fizbuz.txt";
    string line;
    int d1,d2,len;
    int i =0;
    int res1[10], res2[10], length[10];
    ifstream read (filename.c_str());
    if (read.is_open())
    {
        // while(read>>d1>>d2>>len);
        // {
        //     res1[i] = d1;
        //     res2[i] = d2;
        //     length[i] = len;
        //     i++;
        // }
        while (!read.eof())
        {
            read>>d1>>d2>>len;
            res1[i] = d1;
            res2[i] = d2;
            length[i] = len;
        }
        read.close();
    }
    else
    {
        cout << "unable to open file\n";
    }
    for (int j = 0; j < 10;j++)
    {
        cout<< res1[j] << " " << res2[j] << " " << length[j] << '\n';
    }

}

Both of the while loops perform the same in the output function at the bottom. The last line of fizbuz.txt will be returned to the first elements of res1,res2 and length, and the remaining elements of all 3 are psuedorandom values, presumably from whatever program was using that memory block before. ex output below

4 9 25
32767 32531 32767
-1407116911 4195256 -1405052128
32531 0 32531
0 0 1
0 1 0
-1405052128 807 -1404914400
32531 1 32531
-1405054976 1 -1404915256
32531 0 32531

Solution

  • The first version should work except that you need to remove the ; in the while line.

    while (read >> d1 >> d2 >> len);
                                   ^