定义一个课程结构体(成员有课程,有名字,上课时间以及总课时数),往文件写入三个课程后并输出
时间: 2024-03-06 08:48:42 浏览: 25
好的,以下是一个示例代码,定义了一个课程结构体,并将三个课程写入到文件中,并读取文件内容输出到控制台上:
```c++
#include <iostream>
#include <fstream>
#include <string>
struct course {
int id; // 课程编号
std::string name; // 课程名称
std::string time; // 上课时间
int total_hours; // 总课时数
};
int main() {
// 定义三个课程
course c1 = {1, "C++ Programming", "Monday 9:00-11:00", 20};
course c2 = {2, "Data Structures", "Wednesday 13:30-15:30", 24};
course c3 = {3, "Algorithms", "Friday 10:00-12:00", 30};
// 将课程写入到文件中
std::ofstream ofs("courses.txt");
ofs << c1.id << " " << c1.name << " " << c1.time << " " << c1.total_hours << std::endl;
ofs << c2.id << " " << c2.name << " " << c2.time << " " << c2.total_hours << std::endl;
ofs << c3.id << " " << c3.name << " " << c3.time << " " << c3.total_hours << std::endl;
ofs.close();
// 从文件中读取课程并输出到控制台
std::ifstream ifs("courses.txt");
int id, total_hours;
std::string name, time;
while (ifs >> id >> name >> time >> total_hours) {
std::cout << "ID: " << id << ", Name: " << name << ", Time: " << time << ", Total hours: " << total_hours << std::endl;
}
ifs.close();
return 0;
}
```
以上代码中,我们首先定义了一个 `course` 结构体,然后定义了三个课程并将其写入到文件 `courses.txt` 中。接着我们从文件中读取课程信息,并输出到控制台上。运行程序后,输出结果如下:
```
ID: 1, Name: C++ Programming, Time: Monday 9:00-11:00, Total hours: 20
ID: 2, Name: Data Structures, Time: Wednesday 13:30-15:30, Total hours: 24
ID: 3, Name: Algorithms, Time: Friday 10:00-12:00, Total hours: 30
```
这表明我们已经成功地将三个课程信息写入到了文件中,并从文件中读取了这些信息。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)