C++从文件读取信息并将其按顺序存入指向的数组
时间: 2024-09-07 10:05:24 浏览: 82
在C++中,从文件读取信息并将数据存入数组可以通过使用标准库中的输入输出流(iostream)和文件流(fstream)类来实现。下面是一个简单的例子,演示了如何从文本文件中读取数据并存入一个数组中:
```cpp
#include <iostream>
#include <fstream>
#include <string>
int main() {
// 声明一个足够大的数组来存储数据
const int MAX_SIZE = 100;
int array[MAX_SIZE];
int count = 0; // 用于记录读取的数据个数
// 打开文件
std::ifstream file("data.txt");
if (!file.is_open()) {
std::cerr << "无法打开文件!" << std::endl;
return 1;
}
// 从文件中读取数据
int value;
while (file >> value) { // 读取整数直到文件末尾
if (count < MAX_SIZE) {
array[count++] = value; // 将读取的值存入数组
} else {
std::cerr << "数组已满,无法存入更多数据!" << std::endl;
break;
}
}
// 关闭文件
file.close();
// 输出读取的数据,验证是否成功
std::cout << "读取的数据有:" << std::endl;
for (int i = 0; i < count; ++i) {
std::cout << array[i] << std::endl;
}
return 0;
}
```
上面的代码演示了如何打开一个名为"data.txt"的文件,从文件中逐行读取整数,并将它们按顺序存入名为`array`的整数数组中。需要注意的是,这里假设文件中的数据都是整数,并且用空格、换行符等分隔。此外,代码中还包含了一些基本的错误检查,例如检查文件是否成功打开。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![text/plain](https://img-home.csdnimg.cn/images/20250102104920.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)