C++读取txt文档到数组

用C++从txt文件中读取 x 行 y 列的数据到数组中。


//读取数据到 double数组
#include <iostream>
#include <fstream>
 
using   namespace   std;
 
int   main()
{
     double   array[27][30]={0.0};//如果数据量过大 则需要把 array 定义成static类型,
                                //因为默认的堆栈大小容量不够,可以放到静态存储区
    
  • 13
    点赞
  • 91
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
读取txt文档的三维数组可以通过以下步骤实现: 1. 打开txt文件,读取其中的数据并存储到一个字符串中。 2. 将字符串按照空格或换行符进行分割,得到每个数据的值。 3. 将得到的数据按照指定的行列和深度进行存储,构成一个三维数组。 以下是一段示例代码: ```c++ #include <iostream> #include <fstream> #include <sstream> #include <vector> using namespace std; int main() { ifstream file("data.txt"); if(!file) { cout << "Failed to open file." << endl; return 0; } // 读取文件内容 stringstream buffer; buffer << file.rdbuf(); string contents = buffer.str(); // 将字符串按照空格或换行符进行分割 vector<string> values; stringstream ss(contents); string value; while(ss >> value) { values.push_back(value); } // 构造三维数组 int rows = 3; // 行数 int cols = 4; // 列数 int depth = 2; // 深度 int index = 0; int arr[rows][cols][depth]; for(int k = 0; k < depth; ++k) { for(int i = 0; i < rows; ++i) { for(int j = 0; j < cols; ++j) { arr[i][j][k] = stoi(values[index]); ++index; } } } // 输出结果 for(int k = 0; k < depth; ++k) { cout << "Depth " << k << ":" << endl; for(int i = 0; i < rows; ++i) { for(int j = 0; j < cols; ++j) { cout << arr[i][j][k] << " "; } cout << endl; } cout << endl; } return 0; } ``` 其中,data.txt文件内容如下: ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ``` 程序输出为: ``` Depth 0: 1 2 3 4 5 6 7 8 9 10 11 12 Depth 1: 13 14 15 16 17 18 19 20 21 22 23 24 ```
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值