2012-04-29 69 views
0

我有一个包含两个字符串,一个长整数和一个整数数组的结构向量。创建所述结构体时,我将数组中的每个元素初始化为0.我的问题是,我将如何去为数组中的每个元素分配不同的值?我试图使用交换和分配,但它们更多的是具有两个1维矢量,而不是2维矢量,并且我只想在给定时间更改某个结构中的值。请帮忙?谢谢!结构向量的交换内容C++

如果你想看到一些代码,这是我到目前为止有:

//this is my struct 
typedef struct { 
    string lastName; 
    string firstName; 
    long int gNumber; 
    int grades[12]; 
} student; 

//this function takes data from a file, fills it into a struct, then pushes back into //vector 

bool loadStudentData(vector<student> &studentRecords, ifstream *inFile, student tempStudent) { 
    int idx = 0; 
    stringstream fileLine; 
    string line; 
    bool isLoaded = true;  
    char letterInGNumber; 
    while (getline(*inFile, line)) { 
    fileLine << line; 
    getline(fileLine, tempStudent.lastName, ','); 
    getline(fileLine, tempStudent.firstName, ','); 
    fileLine >> letterInGNumber; 
    fileLine >> tempStudent.gNumber; 
    for (idx = 0; idx <= 11; idx++) { 
     tempStudent.grades[idx] = 0; 
    } 
    studentRecords.push_back(tempStudent); 
    fileLine.flush(); 
    } 
    return isLoaded; 
} 

//this function is trying to take things from a second file, and if the Gnumber(the //long int) is found in the vector then assign values to the grade array 
void loadClassData(vector<student> &studentRecords, ifstream *inFile) { 
    int idx = 0, idxTwo = 0, idxThree = 0; 
    long int tempGNumber = 0; 
    stringstream fileLine; 
    vector<long int> gNumbers; 
    bool numberFound = false; 
    char letterInGNumber; 
    string line; 
    while (getline(*inFile, line)) { 
    idx++; 
    numberFound = false; 
    fileLine << line; 
    fileLine >> letterInGNumber; 
    fileLine >> tempGNumber; 
    for (idxTwo = 0; idxTwo <= studentRecords.size(); idxTwo++) { 
     if (studentRecords[idxTwo].gNumber == tempGNumber) { 
      numberFound = true; 
      break; 
     } 
    } 
    if (numberFound) { 
     for (idxThree = 0; idxThree <= 11; idxThree++) { 
      //fileLine >> studentRecords[idx].grades[idxThree]; 
      /**********here is the problem, I don't know how to assign the grade values******/ 
     } 
    } 
    else { 
     cout << "G Number could not be found!" << endl << endl; 
    } 
    fileLine.flush(); 
    } 
    return; 
} 

的人?请?

+7

而不是试图描述你的代码,请只是张贴一些实际的说明代码。 –

+0

代码已发布 –

+0

是我的逻辑关闭整个事情,或者我在正确的轨道 –

回答

1

你应该做的,而不是为定义操作>>超载和刚读在。例如,

//assume the following structure when reading in the data from file 
// firstName lastName N n1 n2 n3 ... nN 
ostream& operator>>(ostream& stream, student& s){ 
     stream >> s.firstName; 
     stream >> s.lastName; 
     stream >> s.gNumber 
     for(int i = 0; i < s.gNumber; ++i){ 
     stream >> s.grades[i]; 
     } 
} 

//... in main 
student temp; 
std::vector<student> studentList; 
while(inFile >> temp) studentList.push_back(temp);