Reputation: 969
Weird question and hard to word but lets say I have a 2 files that have a string of what double variables will appear in the file at the top and then the corresponding double variables, something like:
File1 =
A B C D E
1.2 3.4 4.5 5.6 7.8
File2=
B D E
9.8 7.6 5.4
and I have a struct of doubles
struct numb{
double A,B,C,D,E};
is it possible to read in the string in file 1 (A B C D E) and whatever the first value in the string is (A) assign it to the corresponding struct value numb.A.
So then the next file it will read in the first value of the string (B) and assign it to numb.B. I realize this is possible with a bunch of if statements but I was wondering if there is an easier way. The hardest part is the string of variables will always be some combination of A,B,C,D,E. I am programming in C++ VS10
Upvotes: 1
Views: 672
Reputation: 13278
You can create a map with the string to parse as the key, and a pointer to member of the corresponding attribute of your structure as the value.
std::map<std::string, double numb::*> mapLetterToCorrespondingAttribute;
Then parse your file and assign the value to the corresponding member pointed to by the value in your map corresponding to the key being the letter you parsed.
Read this multiple times before you say you don't understand :D
Upvotes: 2
Reputation: 4674
Read the two lines into std::vector<std::string>
and then put them into a map in pairs:
std::vector<std::string> vars; // the split up first line
std::vector<std::string> values; // split up second line
std::map<std::string, double> mapping;
for (int i = 0; i < vars.size(); ++i) {
mapping.insert(std::make_pair(vars[i], boost::lexical_cast<double>(values[i]));
}
If you pre-populate the map mapping
with sensible default values, this should be quite simple. Also, you can substitute the call to boost::lexical_cast<double>
with any conversion method you like.
Upvotes: 0
Reputation: 23058
Declare an array of double in struct numb
.
struct numb {
void setValue(char label, double val) { value[label-'A'] = val; }
double getValue(char label) const { return value[label-'A']; }
double value[5];
};
Then, you could perform:
numb n;
n.setValue('A', 1.2);
double A = n.getValue('A');
Upvotes: 0
Reputation: 363547
A switch
is probably the easiest way to do this.
void set_member(numb &n, char member, double value)
{
switch (member) {
case 'A':
n.A = value;
break;
case 'B':
n.B = value;
break;
// etc.
default:
// handle error
}
}
Upvotes: 0