c++怎么存储信息到文件
时间: 2023-12-15 22:04:40 浏览: 37
C++可以通过文件流来存储信息到文件中。一般情况下,我们使用ofstream类来写文件,使用ifstream类来读文件。
下面是一个示例程序,演示如何使用C++将信息存储到文件中:
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
//打开文件
ofstream outfile("example.txt");
//写入文件
outfile << "Hello World!" << endl;
outfile << "This is an example." << endl;
//关闭文件
outfile.close();
return 0;
}
```
上面的程序中,我们首先创建了一个ofstream对象outfile,并将其绑定到文件example.txt上。然后我们使用“<<”运算符向文件中写入了两行信息,并最终使用close()函数关闭了文件。
当然,这只是最简单的一个例子,实际应用中可能会涉及到更多的文件操作,比如打开已有文件、读取文件内容等等。
相关问题
c++读取文件信息到数组
可以使用标准库中的fstream头文件来读取文件信息到数组中。
以下是一个简单的示例代码:
```c++
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main() {
ifstream inFile("example.txt"); // 打开文件
vector<int> arr;
int temp;
while (inFile >> temp) { // 从文件中读取数据,直到到达文件末尾
arr.push_back(temp); // 将读取的数据存入数组中
}
inFile.close(); // 关闭文件
// 输出数组内容
for(int i=0; i<arr.size(); i++){
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
注意:这里使用了vector来存储读取的数据,因为数组在声明时需要指定大小,而vector可以动态地添加元素。
C++读取文件信息到数组
可以使用标准库中的fstream头文件来读取文件信息到数组中。
以下是一个简单的示例代码:
```c++
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main() {
ifstream inFile("example.txt"); // 打开文件
vector<int> arr;
int temp;
while (inFile >> temp) { // 从文件中读取数据,直到到达文件末尾
arr.push_back(temp); // 将读取的数据存入数组中
}
inFile.close(); // 关闭文件
// 输出数组内容
for(int i=0; i<arr.size(); i++){
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
注意:这里使用了vector来存储读取的数据,因为数组在声明时需要指定大小,而vector可以动态地添加元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)