while (getline(inFile, line)) { istringstream iss(line); string type; iss >> type; if (type == "student") { string name, gender; int id, age; iss >> name >> id >> age >> gender; Student student = { name, id, age, gender }; students.push_back(student); } else if (type == "course") { string name, teacher; int id, credit; iss >> name >> id >> credit >> teacher; Course course = { id, name, credit, teacher }; courses.push_back(course); } else if (type == "score") { int studentId, courseId, score; iss >> studentId >> courseId >> score; Score s = { studentId, courseId, score }; scores.push_back(s); } } 此段代码有错误不能运行请帮忙修正
时间: 2024-02-25 21:57:45 浏览: 164
information-source-for-the-host.rar_The Information_主机基本信息
此段代码没有定义变量 `inFile`,需要在之前定义并打开一个输入文件流对象,如下所示:
```c++
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
struct Student {
string name;
int id;
int age;
string gender;
};
struct Course {
int id;
string name;
int credit;
string teacher;
};
struct Score {
int studentId;
int courseId;
int score;
};
int main() {
ifstream inFile("data.txt");
if (!inFile.is_open()) {
cerr << "Error: cannot open input file!" << endl;
return 1;
}
vector<Student> students;
vector<Course> courses;
vector<Score> scores;
string line;
while (getline(inFile, line)) {
istringstream iss(line);
string type;
iss >> type;
if (type == "student") {
string name, gender;
int id, age;
iss >> name >> id >> age >> gender;
Student student = { name, id, age, gender };
students.push_back(student);
} else if (type == "course") {
string name, teacher;
int id, credit;
iss >> name >> id >> credit >> teacher;
Course course = { id, name, credit, teacher };
courses.push_back(course);
} else if (type == "score") {
int studentId, courseId, score;
iss >> studentId >> courseId >> score;
Score s = { studentId, courseId, score };
scores.push_back(s);
}
}
inFile.close();
// do something with the data
return 0;
}
```
上述代码定义了一个名为 `inFile` 的输入文件流对象,并在读取数据之前打开了一个名为 `data.txt` 的输入文件。此外,还加上了错误处理,当文件无法打开时会输出错误信息并退出程序。
阅读全文