如何解决使用循环将不同的值分配给不同的结构变量
我有一个如下的考生结构(每个人都有1个id和他们对不同主题的分数):
struct Examinee
{
string id;
float math,literature,physic,chemistry,biology,history,geography,civic_education,natural_science,social_science,foreign_language;
};
现在,我想编写一个从字符串中读取不同值并将其分配给考生的函数。字符串如下所示(每个信息都用逗号分隔):
BD1200001,9,4.0,5.0,10,3.5,7.5,4.25,7.0,7.75,9.25,2.0
这是我到目前为止所做的:
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;
}
问题是:我可以像上面的while循环那样将每个分数分配给每个主题吗?我怎样才能做到这一点?如果不是,那么手动分配每个分数是唯一的方法吗?
解决方法
我将更改Examinee
的设计。遵循以下原则:
struct Examinee
{
enum Subject {kSubjMath,kSubjLiterature,...,kSubjForeignLanguage,kSubjCount};
string id;
float scores[kSubjCount];
};
这样,您可以循环访问分数,例如
for (int subj = 0; subj < Examinee::kSubjCount; ++subj) {
examinee.scores[subj] = some_score;
}
或以examinee.scores[Examinee::kSubjLiterature]
的身份访问特定分数
如果您无法或不愿意更改Examinee
,则可以在本地进行模拟:
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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。