1.设计一学生注册信息登记程序,该程序要求达到以下要求: a.学生信息包括姓名,学号,性别; b.学生信息要求能够循环从键盘输入,如果输入0 0 0,则退出输入; c.将所有输入的学生信息按文本文件的方式存储到一名为stureginfo.txt的文件中,文件中存储信息的格式如下: 姓名:张三 学号:10521030146 性别:男 d.停止输入后,程序读出存储到stureginfo.txt文件中的所有信息,并显示在屏幕上。用c++写
时间: 2024-02-05 10:13:48 浏览: 19
以下是一种可能的实现方式:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Student {
string name;
string id;
string gender;
};
int main() {
ofstream outfile("stureginfo.txt");
if (!outfile.is_open()) {
cout << "Failed to open file stureginfo.txt" << endl;
return 1;
}
Student student;
while (true) {
cout << "Enter student information (name id gender): ";
cin >> student.name >> student.id >> student.gender;
if (student.name == "0" && student.id == "0" && student.gender == "0") {
break;
}
outfile << "姓名:" << student.name << " 学号:" << student.id << " 性别:" << student.gender << endl;
}
outfile.close();
ifstream infile("stureginfo.txt");
if (!infile.is_open()) {
cout << "Failed to open file stureginfo.txt" << endl;
return 1;
}
string line;
while (getline(infile, line)) {
cout << line << endl;
}
infile.close();
return 0;
}
```
程序首先尝试打开文件stureginfo.txt,如果无法打开则输出错误信息并退出。然后它使用一个结构体Student来存储每个学生的姓名、学号和性别。程序进入一个循环,每次循环从键盘输入一个学生的信息,如果输入了0 0 0则退出循环,否则将该学生的信息按照指定的格式写入文件stureginfo.txt中。写入完毕后关闭文件。
接着程序再次打开文件stureginfo.txt进行读取,如果无法打开则输出错误信息并退出。程序使用getline函数一行一行地读取文件中的内容并输出到屏幕上。读取完毕后关闭文件。
注意,本程序没有对输入的学生信息进行任何校验和处理,例如输入的学号是否符合规范等。在实际应用中应该考虑到这些问题。
相关推荐
![text/x-c](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)
![](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)