gpt4 book ai didi

c++ - 根据它们在 C++ 中作为矩阵的位置从文件中读取数字

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

我有一个包含数字的大文件,我想根据它们的位置(行、列)提取数字。例如,如果我只想处理前 3 行和 3 列,即 9 个数字。该程序打印第一行的 9 个数字。一旦列索引为 4,我想转到下一行。如何在 C++ 中执行此操作。这是我到目前为止所做的:

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

const int NROWS = 3;
const int NCOLS = 3;
int main()
{
ifstream data;

double Numbers[NROWS][NCOLS];

double Num;

data.open("Input.txt");
for (int i = 0; i<NROWS; ++i)
{
for (int j = 0; j<NCOLS; ++j)
{
data >> Num;
Numbers[i][j]=Num;
cout << Numbers[i][j] << endl;
}
}
data.close();
return 0;
}

最佳答案

您应该在读取每个 NCOLS 列号后跳过行。

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

const int NROWS = 3;
const int NCOLS = 3;
int main()
{
ifstream data;

double Numbers[NROWS][NCOLS];

double Num;

data.open("Input.txt");
for (int i = 0; i<NROWS; ++i)
{
for (int j = 0; j<NCOLS; ++j)
{
data >> Num;
Numbers[i][j]=Num;
cout << Numbers[i][j] << endl;
}
std::string skip;
std::getline(data, skip);
}
data.close();
return 0;
}

关于c++ - 根据它们在 C++ 中作为矩阵的位置从文件中读取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49901744/

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