I'm trying to develop skills in file input/output. And I came out with a small challenge to. I want to hear your ideas regarding it.
So, there is a source text file let's say source.in with the following content:
1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
We have to assign those values to a 2D array. BUT!!! We don't know what is the size of the array should be because we don't know how many raws and how many columns are there in the source file.(just imagine you don't know to make the program work with any sourcefile)
The challenge is to write a program which will be able to determine the exact number of raws and columns in the source file and assign those values as a size of 2D array
int x[lines][columns]
Looking forward to hear your opinions and to see your codes. I won't post mine right away not to stick your mind to the solutions I have (though its a bit wrong)
The point of the exercise is to make your program work not only with files created by you but with any source file. Even those which content we don't know.
A 2D array in C++ must have its second dimension known at compile time. There is no way to construct an object of such type if the size is only known at run time (after reading a file)
You can construct a vector, though:
1 2 3 4 5 6 7 8
std::ifstream f("source.in");
std::vector<std::vector<int>> m;
for(std::string line; getline(f, line); )
{
std::istringstream s(line);
m.emplace_back(std::istream_iterator<int>(s), // (assuming modern compiler, use push_back otherwise)
std::istream_iterator<int>());
}
You can also construct a 1D array of pointers into 1D arrays, which is another data structure that can be accessed using the m[x][y] notation, but that's unnecessarily complicated.