>>if you are using c++
Although the code in the OPs post does reference a "string" object, we'll have to assume for now that this is a C program, as they've posted on the C forum. Maybe the OP can clarify?!
Anyways, here's one way to achieve the goal. Normally I wouldn't give you a complete code answer, but I think it'll be easy than trying to explain what I'm thinking!
Code:
#include <stdio.h>
#include <string.h>
struct Option
{
const char *Name;
int Value;
};
int FindOptionIndex(struct Option *OptionsTable, int Length, const char *Criteria)
{
int i;
for (i = 0; i < Length; i++)
{
if (strcmp(OptionsTable[i].Name, Criteria) == 0)
return i;
}
printf ("Invalid option: >%s<\n", Criteria);
return -1;
}
int main(void)
{
struct Option myOptions[2] = {
{"item1", -1},
{"item2", -1}
};
char SimulatedInput[] = "item2";
int Index;
int i;
if ((Index = FindOptionIndex(myOptions, sizeof(myOptions)/sizeof(*myOptions), SimulatedInput)) != -1)
{
myOptions[Index].Value = 99;
}
for (i = 0; i < sizeof(myOptions)/sizeof(*myOptions); i++)
{
printf ("%s = %d\n", myOptions[i].Name, myOptions[i].Value);
}
return(0);
}
The "struct Option" contains the information for a single option, "myOptions" is an array of these. In main, we initialise the array to have names and default values.
The FindOptionIndex() function searches the array for an entry with a Name element that matches the input criteria. If no match is found, -1 is returned. The code in main() calls this function to determine the index location of a particular option, then sets the appropriate value, in this case to a hard coded value of 99.
In case you don't recognise it, this piece of code:
sizeof(myOptions)/sizeof(*myOptions)
... simply works out the count of elements in the myOptions array, which equates to 2 in this code.