簡體   English   中英

在另一個結構中初始化結構數組

[英]initialize an array of structs inside another struct

我完全迷住了。 如何填充另一個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_recordyear向量發送到一種方法來填充兩個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

    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數組。 然后對於char錯誤,我認為您應該在emp_name上使用字符串作為dataType。

[編輯]將字符串復制到char

strcpy(sort_records[j].employee_stats[j].emp_name, line[j].c_str());

閱讀源: http : //www.cplusplus.com/reference/string/string/c_str/

您的問題是您沒有正確聲明內部結構。

您的代碼應該看起來像這樣(偽代碼):

typedef employee_stats some_type;
Use some_type inside annual_reviews.

其余的都是微不足道的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM