c++ - 使用循环为不同的结构变量分配不同的值
问题描述
我有一个如下的考生结构(每个都有 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;
}
推荐阅读
- javascript - 使用功能组件输入 ReactJS
- javascript - 如何使用 Selenium Java 框架自动化 Shadow DOM
- c++ - 我们什么时候应该编写自己的移动构造函数(移动赋值运算符)
- arrays - 有没有办法在 C 语言的表格形式输出期间处理空格?
- pytorch - sqrt_vml_cpu 未针对“长”实现
- python - 在Python中引用子目录之间文件的正确方法和VSCode设置是什么
- postgresql - 如何使用 date_part 函数将每月的值拆分为每天和国家
- javascript - 是否有可用于 node.js 的 array_walk_recursive php 函数的替代方法?
- android - 根据构建风格从清单中删除权限
- grails - 圣杯4升级