THE CHALLENGE!!!

Hi Lads,

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)
Last edited on
hehe tnx for the challenge,
I'll try to solve it as soon as I fininsh reading "iostream" chapter from my book.

btw, may I ask you where are you from?, cos your nick looks familiar to me :D, you may live near my country?

cheers!
You're welcome!

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.

Good luck to your work. I'm working on it too.
Last edited on
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.


A 2D array in C++ (or C) must have its second dimension known at compile time.
Topic archived. No new replies allowed.