1

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

1

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

A nice addition: Expose this map in your class or provide a method which uses this map for the implementation (even better).
0

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
    }
}

Comments

0

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');

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.