Reputation: 1845
I am trying to load a tab and or whitespace delimited text file into a two dimensional array. The file looks something like this:
1 -3 4
4 -3 7
8 -1 10
I have access to a piece of code that suggests it is permissible to do something such as the following:
int nums[][] = {
#include "matrix.txt"
};
However, whenever I try to compile this code I am obtaining the error:
$ gcc hangserver.c
hangserver.c:10:5: error: array type has incomplete element type
In file included from hangserver.c:11:0:
matrix.txt:1:5: error: expected ‘}’ before numeric constant
$
I know there are less-elegant ways to load this file into an array, however out of pure curiosity I would like to know if it is possible to implement the methodology shown above. Thank you so much for taking the time to answer my question.
Upvotes: 0
Views: 159
Reputation: 70911
There is a conceptual problem in your approach.
If for example you had
1, 2, 3, 4, 5, 6,
How should the compiler know you want a 3x2 or 2x3 or a 1x6 or a 6x1 array?
So it needs to know the number of columns in advance.
For the example above, this
int matrix [][3] = {
# include "data.txt"
};
would do, as well a this:
int matrix [][2] = {
# include "data.txt"
};
and this:
int matrix [][1] = {
# include "data.txt"
};
and this:
int matrix [][6] = {
# include "data.txt"
};
Although you get a compiler warning about missing braces, as (for the 1st case) above data.txt
really should look like:
{1, 2, 3,},{4, 5, 6,},
(The trailing ,
s are optional.)
To fully steer this via files from the outside do:
int matrix[][
# include "colums.txt"
] = {
# include "data.txt"
};
Here the content of columns.txt
would just be an integer describing the intended number of columns the data from data.txt
shall be broken down to.
Upvotes: 2
Reputation: 2620
The line expands into:
int nums[][] = {
1 -3 4
4 -3 7
8 -1 10
};
which is not acceptable C and C++ syntax. Try with changing the matrix.txt file into
{1, -3, 4},
{4, -3, 7},
{8, -1, 10}
Upvotes: 1
Reputation: 2744
There must be a comma after every number and every row has to be inside a {}
:
{ 1, -3, 4 },
{ 4, -3, 7 },
{ 8, -1, 10 }
Upvotes: 4