Reputation: 276
I'm coding in C and I have a string which consists of values such like this
e=3213213123
n=321312321321321
How do I use regular expressions in order to assign int e
and int n
these values from a string?
Upvotes: 1
Views: 115
Reputation: 399949
There's no way to directly match the string to a variable name; variable names are strictly a compile-time concept that are not present at run-time.
You need to do the matching (against a run-time list or array of variable names, probably), parsing of the value to be assigned, and finally the assignment as separate steps.
There's little point in using regular expressions here, something way simpler such as:
char vname[32];
int value;
if(sscanf("%30s=%d", vname, &value) == 2)
{
if(strcmp(vname, "e") == 0)
e = value;
else if(strcmp(vname, "n") == 0)
n = value;
else
fprintf(stderr, "**Unknown variable name '%s'\n", vname);
}
should do it. Note that the above simply hard-codes the "list" of variable names, which is not very scalable if you need to support a large (more than three) number of variables.
Upvotes: 0
Reputation: 409356
Skip over the "e="
part, and use strtoll
. No regular expressions needed.
Upvotes: 1
Reputation: 9484
atoi()
which converts the string to integer.
strtol()
- convert a string to a long integer.
Read man pages of these functions and choose according to your need.
The atoi() function converts the initial portion of the string pointed to by nptr to int. The behavior is the same as
strtol(nptr, (char **) NULL, 10);
except that atoi() does not detect errors.
Upvotes: 0