4.信息存储:程序退出时将信息存储到硬盘上,开启时从硬盘读取信息。c++怎么写代码
时间: 2024-05-04 16:19:51 浏览: 14
在C++中,可以使用文件流(fstream)来实现信息的存储和读取。具体可以参考以下代码:
存储信息到文件:
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream out("info.txt"); // 创建输出文件流对象
if (out.is_open()) { // 判断文件是否打开成功
out << "Hello World!" << endl;
out << 123 << endl;
out.close(); // 关闭文件
}
else {
cout << "文件打开失败!" << endl;
}
return 0;
}
```
从文件读取信息:
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream in("info.txt"); // 创建输入文件流对象
if (in.is_open()) { // 判断文件是否打开成功
string str;
int num;
in >> str >> num;
cout << str << endl;
cout << num << endl;
in.close(); // 关闭文件
}
else {
cout << "文件打开失败!" << endl;
}
return 0;
}
```
这里使用了ofstream和ifstream分别表示输出文件流和输入文件流,使用is_open()函数判断文件是否打开成功,使用close()函数关闭文件。