Arashdn
Arashdn

Reputation: 731

Coping a file content into a multidimensional array

I have created a c++ application to read content of a file into an array:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;



int main()
{
    fstream myfile;
    myfile.open("myfile.txt");
    int a[3];
    int counter = 0;
    char s[10];
    while (!myfile.eof())
    {
        myfile.getline(s, 10,';');
        a[counter]=atoi(s);
        counter++;
    }

    for (int i = 0 ; i<3 ; i++)
        cout << a[i]<<endl;

    cin.get();
}

and content if my file is:

15;25;50

and it's working fine

My question is : If I change file to:

15;25;50

12;85;22

How can I read all of file into a 3*2 array?

Upvotes: 1

Views: 220

Answers (1)

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

You have two delimiters, ; and newline (\n), which complicates matters a bit. You can read a complete line and split this line afterwards. I would also suggest using std::vector instead of plain arrays

std::vector<std::vector<int> > a;
std::string line;
while (std::getline(myfile, line)) {
    std::vector<int> v;
    std:istringstream ss(line);
    std::string num;
    while (std::getline(ss, num, ';')) {
        int n = atoi(num);
        v.push_back(n);
    }

    a.push_back(v);
}

Using plain arrays is possible, too. You must then make sure, you don't overwrite the array, when you have more lines than the array permits.

If you have always three numbers in one row, you can also make use of this and split the first two numbers at ; and the third one at \n

int a[2][3];
for (int row = 0; std::getline(myfile, s, ';'); ++row) {
    a[row][0] = atoi(s);
    std::getline(myfile, s, ';'));
    a[row][1] = atoi(s);
    std::getline(myfile, s));
    a[row][2] = atoi(s);
}

But this will fail of course, if you have more than three numbers in a row or, worse yet, have more than two rows.

Upvotes: 2

Related Questions