有没有办法从包含学生记录但由不同字符分隔的文件中读取?我的文字如下:
125 {John_BROWN_Biology} {100_81}
245 {Amanda_SMITH_Chemistry} {83_74}
436 {Michael_CLARK_Calculus} {35_48}
我必须将它们存储在单独的数组中,以便计算它们的平均值并按升序排列。我以这种方式用 C++ 编写了代码:
int rank;
char st_info[SIZE];
int grades[SIZE];
bool success1 = false;
bool success2 = false;
bool success3 = false;
ifstream inFile;
inFile.open("records.txt");
string line;
int i=0, j=0;
while (!inFile.getline(rank, 30, '{').eof){
inFile.getline(st_info, SIZE, '_');
inFile.getline(words_array, SIZE, '_');
}
while (!success1)
{
getline(inFile,Line,'{'); // get values for info array
stringstream iss1;
iss1 << Line; //Put the string into a stream
iss1 >> rank; //To send data as an int.
cout << "STUDENT NUMBER:" << rank << " ";
while (!success2){
// for the info in {} part
getline(inFile,Line,'_');
stringstream iss;
iss << Line;
iss >> st_info[i];
cout <<"STUDENT INFO:" << st_info[i] << " ";
i++;
if (getline(inFile,Line,'}')){
stringstream iss2;
iss2 << Line;
iss2 >> st_info[i];
cout << st_info[i] << " ";
i=0;
success2 = true;
}
}
getline(inFile,Line,'{');
stringstream iss3;
iss3 << Line;
iss3 >> grades[j];
cout << "GRADES: "<< grades[i] << " ";
j++;
while (!success3){
getline(inFile,Line,'_');
stringstream iss4;
iss4 << Line;
iss4 >> grades[j];
cout << grades[i] << " ";
j++;
if (getline(inFile,Line,'}')){
stringstream iss5;
iss5 << Line;
iss5 >> grades[j];
cout << grades[i] << " ";
j=0;
success3 = true;
}
}
}
但是,作为输出,我得到:
1 J 100
2 A 100
4 M 100
试图修复,但它变得更糟。有谁能帮忙吗?提前致谢。