Reputation: 141
How do i parse key-value string in C and assign it to appropriate variable?
I.e. we will pass this string to a program:
x = 193
and it will assign value to appr. variable, so
printf("%i", x);
produces
193
Upvotes: 1
Views: 4318
Reputation: 4462
Given
char keyname[32];
int val;
where we want to store the name of the keyname and value of the integer assignment, and a string of the example format const char * str = "x = 193"
we could use sscanf()
C library function to do the parsing for us:
sscanf(str, "%32[^=]=%d", keyname, &val)
Note that for example str = " x = 193"
will be store string " x "
to keyname
so you still need to get rid of the extra spaces if you want flexible syntax with regards to spaces around the assignment and before the variable name.
The sscanf()
will return the number of successful conversions, so you should test that it returns 2
in our case.
Once you got the variable name and its integer value stored in keyname
and val
, you can do like @unwind above suggest to see which variable you should assign val
to, testing with strcmp
. If you have a lot of fixed name variables, you could have a table and use a look-up function to make this prettier than one heck of an unmaintainable and error-prone long list of if
statements.
Upvotes: 7
Reputation: 399793
You can't magically introduce variables at run-time. When a C program is running, the names of the variables are long gone, the compiler needs that information to build the code but the CPU doesn't need it to run the code.
You're going to have to strcmp()
against the known variable names, and assign accordingly. To optimize this (for many names values), you can of course use something like a hash table to store pairs of names and integers holding values.
Upvotes: 1