I'm asking this question because the solutions I found to similar questions, here on stackoverflow, didn't allow me to solve my problem. I have a .txt
file which is as follow:
VarA 10.0 20.0 30.0
VarBB 10
VarCz 1 2 3 4
VarDab 10 20 30 40 50
...
I'm trying to output (e.g. store them in a variable) the numbers associated to a specific variable using the sscanf
function. For example, when looking for the string VarDab
in the file, I want to store the numbers 10, 20, 30, 40, 50
in a variable. Because the number of numbers found for a specific string variable is not constant, I was trying to use the sscanf function in a loop. However, I'm not getting the result that I want. The code I have done so far:
FILE *fid;
char nameOfVariable[] = "VarDab";
int i;
while(!feof(fid))
{
fgets(Line, maxLengthOfLine, fid);
sscanf(Line, "%s", varString);
if (strcmp(nameOfVariable, varString) == 0)
{
for (i = 0; i < maxLengthOfLine; i++)
{
sscanf(Line, "%lf%n", &varNumbers[i]);
}
}
}
flcose(fid);
EDIT
From the comments, I was able to modify my current implementation by adding an offset to the Line
at each increment in the loop. It seems to work:
FILE *fid;
char nameOfVariable[] = "VarDab";
int i;
int variableIsFound = 1;
int offset = 0;
int numberOfNumbers = 5;
while(fgets(Line, maxLengthOfLine, fid) != NULL && variableIsFound)
{
sscanf(Line, "%s %n", varString, &offset);
if (strcmp(nameOfVariable, varString) == 0)
{
Line += offset;
for (i = 0; i < numberOfNumbers; i++) {
sscanf(Line, "%lf %n", &y[i], &offset);
Line += offset;
}
variableIsFound = 0;
}
}
fclose(fid);