gpt4 book ai didi

c++ - 从文件中读取选定范围的行并存储到数组中

转载 作者:行者123 更新时间:2023-11-28 04:37:04 27 4
gpt4 key购买 nike

我有这样一个数据文件

               1.2   0.07  0.3
2.3 1.0 1.1
0.3 2.2 1.1

12.2 0.0 0.0
0.0 20.1 0.0
1.2 0.07 0.3
2.3 1.0 1.1
0.3 2.2 1.1

我需要读取文件并将前 3 行存储到矩阵中

                  1.2   0.07  0.3
A = 2.3 1.0 1.1
0.3 2.2 1.1

并从第4行到末尾进入另一个矩阵

                  12.2  0.0   0.0                   
0.0 20.1 0.0
B = 1.2 0.07 0.3
2.3 1.0 1.1
0.3 2.2 1.1

到目前为止我只能创建第一个矩阵

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

int main()
{
const char * filename = "data.txt";
ifstream is(filename);
if (!is)
{
cout << "Unable to open file: " << filename << endl;
return 1;
}

int height = 3, width = 3;

// Dynamic array
double *vec;
vec = new double*[height];
for (int i = 0; i<height; i++)
vec[i] = new double[width];

// Read the data
for (int i = 0; i<height; i++)
for (int j=0; j< width; j++)
is >> vec[i][j];
if (!is)
cout << "Error reading into array" << endl;

// Display the data
for (int i = 0; i<height; i++)
{
for (int j=0; j< width; j++)
cout << setw(5) << vec[i][j];
cout << endl;
}
cout << "done" << endl;

// Delete the array
for (int i = 0; i<height; i++)
delete [] vec[i];
delete [] vec;

return 0;
}

那么如何跳到第 5 行来创建矩阵 B?我想要一个类似循环的东西(矩阵 A 从 0 到 3,矩阵 B 从 4 到 8)

请提供任何帮助,我们将不胜感激!

最佳答案

如果我没理解错的话,如果你需要在文件刚刚打开时跳过第一个矩阵数据

// Skip the data
double dummy;
for (int i = 0; i<height; i++)
for (int j=0; j< width; j++)
is >> dummy;

(高和宽是针对跳过的矩阵A)

如果您必须在矩阵 A 之后立即读取矩阵 B,则无需跳过任何内容

#include <fstream>    
#include <iomanip>
#include <vector>

using namespace std;

int main()
{
const string filename = "data.txt";
ifstream is(filename);
if (!is)
{
cout << "Unable to open file: " << filename << endl;
return 1;
}

int height = 3, width = 3;

// Dynamic array
vector<double> A(height * width);

// Read the data
for (int i = 0; is && i < height; ++i)
for (int j = 0; j < width; ++j)
is >> A[i * width + j];
if (!is)
cout << "Error reading into array" << endl;

// Display the data
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
cout << setw(5) << A[i * width + j];
cout << endl;
}
cout << endl;

// Delete the array
A.clear();

// reading B
height = 5;

// Dynamic array
vector<double> B(height * width);

// Read the data
for (int i = 0; is && i < height; ++i)
for (int j = 0; j < width; ++j)
is >> B[i * width + j];
if (!is)
cout << "Error reading into array" << endl;

// Display the data
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
cout << setw(5) << B[i * width + j];
cout << endl;
}
cout << endl;
B.clear();

cout << "done" << endl;

return 0;
}

输出

  1.2 0.07  0.3
2.3 1 1.1
0.3 2.2 1.1

12.2 0 0
0 20.1 0
1.2 0.07 0.3
2.3 1 1.1
0.3 2.2 1.1

done
Press any key to continue . . .

关于c++ - 从文件中读取选定范围的行并存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51098691/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com