我完全被难住了。如何填充包含在另一个 struct
中的 struct
数组?
我有两个 struct
:
struct employee_stats{
char emp_name[MAX_NAME_LENGTH];
double salary;
int years_employed;
}
struct annual_reviews{
int year;
struct employee_stats employee[NO_EMPLOYEES];
}
我声明了一个指向 annual_reviews
结构数组的指针
annual_reviews *sort_records = new annual_reviews[num_years];
我有一个 vector
字符串,它从程序前面的文本文件中读取。我将 employee_record
和 year
vector 发送到一个方法来填充两个 struct
void DataSort::load_records(vector<string> employee_record, vector<string> year){
vector<string> line_data;
string word;
//split employee_record by \t and into single line string vector
for(int i = 0; i < employee_record.size(); i++){
stringstream wordstream(employee_records[i]);
while(getline(wordstream, word, '\t')){
if(!word.empty())
line.push_back(word);
}
}
现在,在相同的方法中,我想将此数据添加到我的 struct
s:
for(int j = 0; j < num_years; j++){
sort_records[i].year = atoi(year[i].c_str); //year of record
for(int k = 0; k < NO_EMPLOYEES; k++){
//here is where it all falls apart
sort_records[j].employee_stats[j].emp_name = line[j]; //fill the records
}
}
}
我意识到我没有正确访问内部 struct
但我卡住了,我碰壁了。
我在使用 VS2015 时遇到两个编译错误:
std::basic_string<char,std::char_traits<char>,std::allocator<char>>::c_str':non-standard syntax;use'&'to create a pointer to member
array type 'char[25]' is not assignable
有人能指出我正确的方向吗?我是否需要创建指向成员 struct
的指针?我以为您可以直接为成员编制索引。
谢谢。
最佳答案
用于制作数据类型的结构。
struct employee_stats{
char emp_name[MAX_NAME_LENGTH];
double salary;
int years_employed;
}
struct annual_reviews{
int year;
struct employee_stats[NO_EMPLOYEES];
}
在 annual_reviews 数据类型上,我认为您使用声明了另一种数据类型
struct employee_stats
所以我认为你应该在第二个上将它声明为一个数据数组
struct employee_stats{
char emp_name[MAX_NAME_LENGTH];
double salary;
int years_employed;
}
struct annual_reviews{
int year;
employee_stats employeeData[NO_EMPLOYEEs];
}
在创建变量类型 annual_reviews 之后,我认为您可以访问 employeeData 数组。然后对于字符错误,我认为您应该在 emp_name 上使用字符串作为数据类型。
[编辑] 复制字符串到字符
strcpy(sort_records[j].employee_stats[j].emp_name, line[j].c_str());
阅读来源:http://www.cplusplus.com/reference/string/string/c_str/
关于c++ - 在另一个结构中初始化一个结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35305325/