如何修改该代码#include <iostream> #include <fstream> using namespace std; struct student { char name[30]; int* scores; int avg; }; student* input(char* file, int& stunum, int& hwnum) { ifstream in(file, ios::in); int itemnum; in >> stunum >> hwnum >> itemnum; student* stulist = new student[stunum]; for (int i = 0; i < stunum; i++) { stulist[i].scores = new int[hwnum]; for (int j = 0; j < hwnum; j++) { stulist[i].scores[j] = 0; } } int k; for (int i = 0; i < hwnum; i++) { char name[100]; int time, score; in >> name >> time >> score; int j; for ( j = 0; j < k; j++) { if (strcmp(name, stulist[i].name) == 0) break; } if (j < k) { stulist[k].scores[time - 1] = score; } else { strcpy(stulist[k].name, name); stulist[k].scores[time - 1] = score; k++; } } in.close(); return stulist; } int main() { int stunum, hwnum; student* stulist = input("score.txt", stunum, hwnum); for (int i = 0; i < stunum; i++) { cout << stulist[i].name << "\t"; for (int j = 0; j < hwnum; j++) cout << stulist[i].scores[j] << "\t"; cout << endl; } return 0; }
时间: 2024-03-03 16:52:29 浏览: 86
#include_iostream.h_
4星 · 用户满意度95%
这段代码可以通过以下方式进行修改:
1. 在程序开头添加头文件#include <cstring>,以使用strcmp函数。
2. 在函数input的开头将变量k初始化为0。
3. 在函数input中,将stulist[k]改为stulist[j]。
4. 将程序中的所有空格、制表符和换行符替换为单个空格,以保持代码的整洁性。
修改后的代码如下:
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
struct student {
char name[30];
int* scores;
int avg;
};
student* input(char* file, int& stunum, int& hwnum) {
ifstream in(file, ios::in);
int itemnum;
in >> stunum >> hwnum >> itemnum;
student* stulist = new student[stunum];
for (int i = 0; i < stunum; i++) {
stulist[i].scores = new int[hwnum];
for (int j = 0; j < hwnum; j++) {
stulist[i].scores[j] = 0;
}
}
int k = 0;
for (int i = 0; i < hwnum; i++) {
char name[100];
int time, score;
in >> name >> time >> score;
int j;
for (j = 0; j < k; j++) {
if (strcmp(name, stulist[j].name) == 0)
break;
}
if (j < k) {
stulist[j].scores[time - 1] = score;
}
else {
strcpy(stulist[k].name, name);
stulist[k].scores[time - 1] = score;
k++;
}
}
in.close();
return stulist;
}
int main() {
int stunum, hwnum;
student* stulist = input("score.txt", stunum, hwnum);
for (int i = 0; i < stunum; i++) {
cout << stulist[i].name << "\t";
for (int j = 0; j < hwnum; j++)
cout << stulist[i].scores[j] << "\t";
cout << endl;
}
return 0;
}
阅读全文