Hi, I have a script that uses several variables. I first give all these variables a value. I then want the script to read a textfile and if it finds the variables replace the value set in the program with the value in the textfile.
The textile looks like this:
1 2 3 4
Variable1
10
Variable2
30
I was able to write a code that stores all values and variable names in the following variables:
Hi, Thanks for helping out! I am not sure if you understand my problem.
Just to be clear. In the textfile the variable names can differ. So I need the script to read the variable name and value from the textfile and then assign the value to the variable with the name specificed in the textfile.
I am not familiar with maps and will look into that.
Basically I declare some variables and I want to be able to easily change a few without having to rebuild the executable every time.
It now works. To deal with the downside you explained I use this command:
if (varmap["variable1"] != NULL){ variable1 = varmap["variable1"]; }
It is a bit dirty though because now I have to retype this piece of code for all variable names (About 20) and it does not work if the value in the textfile is 0.
How can I fix it so that an input of 0 will also be accepted but not filling it in at all won't?
How can I fix it so that an input of 0 will also be accepted but not filling it in at all won't?
Note that the map::[] operator always returns a reference, so it will never return a null. If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. http://www.cplusplus.com/reference/map/map/operator[]/
void load_variable (constchar * varname, int & val)
{ map<string,int>::iterator iter;
iter = varmap.find (varname);
if (iter == varmap.end())
return; // not found
val = iter->second; // assign value
}
load_variable ("variable1", variable1);
It is a bit dirty though because now I have to retype this piece of code for all variable names (About 20)
#define LOADVAR(var) load_variable(#var,var) // pass argument as quoted string and as reference
...
int variable1 = 0; // Default value in case not found in text file
LOADVAR(variable1);