Reputation: 591
I have file with numbers.
3
2 15 41
4 1 2 3 4
3 22 11 24
First line show how other lines exists (max 100). Numbers in line can not contain more than 50.
Numbers in lines need to be put into array something like:
line[lineNum][num]
I'm new in C++ and I asking to do this in simplest posible way. I tried doing:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
int kiek;
string str[100][50];
string line;
int a = 0;
int b = 0;
ifstream failas("Duom1.txt");
if (failas.is_open())
{
while (failas)
{
if (a == 29)
{
a = 0;
b++;
}
getline(failas, str[a][b], ' ');
}
a++;
}
cout << str[0][0] << endl;
}
Upvotes: 0
Views: 2197
Reputation: 74058
Read the file line by line and then parse every line by itself.
if (failas.is_open())
{
// read first line
string num_lines;
std::getline(failas, num_lines);
// read lines
for (int i = 0; std::getline(failas, line); ++i)
{
// parse line and insert into array
std::istringstream is(line);
string number;
for (int j = 0; is >> number; ++j)
str[i][j] = number;
}
}
a better approach though, would be to use std::vector
instead of an array:
std::vector<std::vector<int> > all_nums;
...
// read first line
string num_lines;
std::getline(failas, num_lines);
// read lines
while (std::getline(failas, line)) {
// parse line and insert into vector
std::istringstream is(line);
int number;
std::vector<int> line_nums;
while (is >> number)
line_nums.push_back(number);
// add line to vector
all_nums.push_back(line_nums);
}
Upvotes: 2