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

Read numbers from file based on their position as matrix in c++

本文关键字:数字 位置 文件 读取 c++      更新时间:2023-10-16

我有一个包含数字的大文件,我想根据它们的位置(行,列(提取数字。例如,如果我只想处理前 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;
}