Currently trying to parse an input file in C to extract variables.
The input file looks like:
% this is a comment
x 3
% another comment
y 5.0
% one last comment
z 4
x, y and z are predefined variables in my C class. My goal is to parse this file so that int x has the value 3, y has the value 5.0, and z has the value 4. Any line starting with % is ultimately ignored
I've managed to do this using fgets and sscanf - here is the attempt:
while (!feof(inputFile)) {
fgets(ch,500,inputFile);
if (sscanf(ch, "x %d", &x)) {
printf("x: %d\n", x);
} else if (sscanf(ch, "y %lf", &y)) {
printf("y: %lf\n", y);
} else if (sscanf(ch, "z %d", &z)) {
printf("z: %d\n", z);
}
and this prints out the desired results. However now I'm trying to use fgets and strtok because I don't think I can get the above code to work with a matrix (i.e. if I had in the input file (note in this case a will also be predefined in my c file):
a
1 -1 3
2 1 6
9 3 0
I would like to store those values in a 3x3 matrix which I don't think is possible using sscanf (especially if the matrix dimensonality is changeable - however it will always be an n * n matrix). My attempt with using fgets and strtok is:
while (!feof(inputFile)) {
fgets(ch,500,inputFile);
token = strtok(ch, " ");
while (token) {
if (strcmp(token, "x")) {
printf("%s", "x found");
// Here is my problem - how do I look at the next token where the value for x is stored
}
token = strtok(NULL, " ");
break;
}
break;
}
The problem in my code is stated in a comment. I've been thinking about this for a while, trying various things. I think the difficulty comes from understanding how strtok works - initially I was trying to store every token into an array.
Any help is appreciated in helping me work out how I can replicate my existing code to use strtok instead of sscanf so I can then work on parsing matrices.
I know there's a few parsing questions out there but I've seen none that tackle how to parse a matrix as such.
Thanks