I am writing a program. The input file in.txt looks like this:
{ 1, 2, 3 }
In the program, I want to simplify my life and write:
#define MAX_ELEMENTS (20)
int a [ MAX_ELEMENTS ] =
#include "in.txt"
;
instead of parsing in.txt with fopen(), fread()...
What I want is to be able to know in the program how many data elements I actually have, in this example 3. The input file might have fewer or more elements (and changing the input file will require a rebuild, of course). There will be an undefined behavior if the number of elements is bigger than MAX_ELEMENTS - which is expected. I take the responsibility to define MAX_ELEMENTS large enough.
So the related questions are:
- How can I get the number of elements read from the file?
- How can I tell the compiler to initialize the rest of the values in
a[]to 0, if they are not initialized from the file?
My ideas:
- Loop through the values left-to-right and count non-zero values. A significant problem occurs if one of the values "in the middle" is zero.
- Loop right-to-left from the end, skipping zero values, until I find a non-zero value. Bad luck if the last value(s) are zeros.
The worst is if the implicitly initialized values (i.e., not from the file) are non-zeros.