C++读取一维数组的txt文件生成一维数组
时间: 2023-09-03 13:11:07 浏览: 46
可以使用C++的fstream库来读取txt文件中的数据,并将其存储到一维数组中。以下是一个简单的示例代码:
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// 打开txt文件
ifstream infile("data.txt");
if (!infile.is_open()) {
cout << "文件打开失败!" << endl;
return 0;
}
// 读取txt文件中的数据到数组中
int arr[100];
int n = 0;
while (!infile.eof()) {
infile >> arr[n];
n++;
}
// 输出数组中的数据
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
// 关闭文件
infile.close();
return 0;
}
```
在上述代码中,我们首先打开了名为“data.txt”的txt文件,然后使用while循环逐行读取文件中的数据,并将其存储到数组中。最后,我们输出了数组中的数据,并关闭了文件。
相关问题
C++用fopen,fread读取一维数组的txt文件生成一维数组
可以使用C语言中的标准库函数`fopen()`和`fread()`来读取txt文件中的数据,并将其存储到一维数组中。以下是一个简单的示例代码:
```c++
#include <stdio.h>
#include <stdlib.h>
int main() {
// 打开txt文件
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
printf("文件打开失败!\n");
return 0;
}
// 获取文件大小
fseek(fp, 0, SEEK_END);
int size = ftell(fp);
fseek(fp, 0, SEEK_SET);
// 读取txt文件中的数据到数组中
int arr[100];
int n = fread(arr, sizeof(int), size / sizeof(int), fp);
// 输出数组中的数据
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// 关闭文件
fclose(fp);
return 0;
}
```
在上述代码中,我们首先使用`fopen()`函数打开了名为“data.txt”的txt文件,然后使用`fseek()`函数获取了文件大小,并使用`fread()`函数逐个读取文件中的数据,并将其存储到数组中。最后,我们输出了数组中的数据,并关闭了文件。
需要注意的是,`fread()`函数返回的是成功读取的数据元素个数,而不是字节数。因此,在计算读取到的数据个数时,需要将`size`(即文件大小)除以`sizeof(int)`(即每个整数占用的字节数)来得到元素个数。
C++用fopen,fread读取一维数组的txt文件生成一维数组Ad[]
可以按照以下步骤进行操作:
1. 打开txt文件,使用fopen函数,其中第一个参数为文件名,第二个参数为打开文件的方式("r"表示只读)。
```c++
FILE* fp = fopen("filename.txt", "r");
```
2. 读取txt文件中的数据,使用fread函数,其中第一个参数为存储数据的数组的地址,第二个参数为每个数据元素的字节数,第三个参数为要读取的数据元素的个数,第四个参数为文件流。
```c++
int Ad[100];
fread(Ad, sizeof(int), 100, fp);
```
3. 关闭文件,使用fclose函数。
```c++
fclose(fp);
```
完整代码如下:
```c++
#include <stdio.h>
int main() {
FILE* fp = fopen("filename.txt", "r");
int Ad[100];
fread(Ad, sizeof(int), 100, fp);
fclose(fp);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)