0

I have a struct of Examinee like below (each has 1 id and their scores of different subjects):

struct Examinee
{
    string id;
    float math, literature, physic, chemistry, biology, history, geography, civic_education, natural_science,
          social_science, foreign_language;
};

Now i want to write a function that reads from a string different values and assign them to an Examinee. The string looks like this (each info is separated by a comma):

BD1200001,9,4.0,5.0,10,3.5,7.5,4.25,7.0,7.75,9.25,2.0

This is what i have done so far:

Examinee readExaminee(string line_info) {

//turn line_info to char*
    int Line_info_length = line_info.length();
    char* info = new char[Line_info_length + 1];
    strcpy(info, line_info.c_str());

//create examinee
    Examinee examinee;

//read id into examinee by token
    char* token = strtok(info, ",");
    examinee.id = token;

//read score and assign to subjects
    while (token != NULL)
    {
        float score = strtof(token, NULL);

        //assign score to appropriate subject

        token = strtok(NULL, ",");
    }

    delete[] info;
    return examinee;
}

The question is: Can i assign each score to each subject in while loop like above? How can i do that? If not, is assigning each score manually the only way?

1
  • Because float fields lay in memory in order, you may assign to *(&math + i) in loop. But I do not suggest to do things like that. I would use map<string, float> scors and obtain string from some build-in array or csv headers string headers[]{"math",...} and assign in loop to score[headers[i]] = val[i] . Commented Nov 8, 2020 at 14:12

1 Answer 1

2

I'd change the design of Examinee. Something along these lines:

struct Examinee
{
  enum Subject {kSubjMath, kSubjLiterature, ..., kSubjForeignLanguage, kSubjCount};
  string id;
  float scores[kSubjCount];
};

This way you can access scores in a loop, e.g.

for (int subj = 0; subj < Examinee::kSubjCount; ++subj) {
 examinee.scores[subj] = some_score;
}

Or access specific score as examinee.scores[Examinee::kSubjLiterature]


If you are unable or unwilling to change Examinee, you can sort of simulate this locally:

Examinee examinee;
float* scores[] = {&examinee.math, &examinee.literature, ..., &examinee.foreign_language};
for (int subj = 0; subj < std::extent_v<scores>; ++subj) {
  *scores[subj] = some_value;
}
Sign up to request clarification or add additional context in comments.

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.