This method is creating my dynamic allocated matrix that I have to read it from a file. I managed finding the columns for every row from the file and initialize my matrix, but I don't know how to read now the values and introduce them into the matrix. The number of neighbourhoods(noCartiere) is generated random from 2 to 14. The number of rows is "noCartiere", the columns is "noStrazi" and "noLocuitori" are the values from the txt file.
void alocaTablou(int& noCartiere, int& noStrazi, int**& noLocuitori)
{
srand(time(NULL));
noCartiere = rand() % 13 2;
cout << "noCartiere generat random este: " << noCartiere << endl;
ifstream f("Text.txt");
string line, word;
noLocuitori = new int* [noCartiere];
int i = 0;
while (getline(f, line))
{
noStrazi = 0;
istringstream iss(line, istringstream::in);
while (iss >> word)
{
noStrazi ;
}
noLocuitori[i] = new int[noStrazi];
i ;
}
}
My Text.txt is:
499 50 79 300
76 89
10 80 80 10 10
689 78 202 34
976 234 566 80
877 590 23 10 10 10
30 59 73 189 200 500 600 700
CodePudding user response:
The solution is to use vectors. More specifically a vector of vectors of integers: std::vector<std::vector<int>>
.
Using vectors, you can also skip the inner reading loop completely, and instead use std::istream_iterator
to initialize (and add) the inner vector directly.
Something like this:
std::vector<std::vector<int>> noLocuitori;
std::string line;
while (std::getline(f, line))
{
std::istringstream iss(line);
noLocuitori.emplace_back(std::istream_iterator<int>(iss),
std::istream_iterator<int>());
}