【问题标题】:My c++ program won't read multiple files from the command line我的 C++ 程序不会从命令行读取多个文件
【发布时间】:2015-12-25 15:34:29
【问题描述】:

我有一个 c++ 程序,用于读取两个表示矩阵的文件。它只会读入其中一个文件。这两个文件都只包含一个浮点矩阵。该程序旨在读取两个矩阵并将它们相乘并将结果打印到命令行。这是程序的代码。

#include <fstream>
#include <iostream>

using std::cin;
using std::cout;
using std::cerr;
using std::endl;
using std::ofstream;

#include <math.h>
#include <stdlib.h>

void readArr(int, int, double **);
void multArrs(int, double **, int, double **, int, double **);
void printResult(int, double **, int);

int main(int argc, char *argv[])
{
  //read in the number of rows and columns
  int ar = atoi(argv[1]);
  int ac = atoi(argv[2]);
  int br = atoi(argv[3]);
  int bc = atoi(argv[4]);

  if (ac != br)
  {
    cerr<< "Matrix dimensions mismatch; exiting.\n";
    exit(-1);
  }

  // reserve space for the three arrays
  double **A = new double*[ar]; // each el. of this points to a row of A
  for (int i = 0; i < ar; i++)
    A[i] = new double[ac];  // a row of 'ac' floats

  double **B = new double*[br];
  for (int i = 0; i < br; i++)
    B[i] = new double[bc];  // a row of 'bc' floats

  double **C = new double*[ar];
   for (int i = 0; i < ar; i++)
    C[i] = new double[bc];  // each el. of this points to a row of C

  readArr(ar, ac, A);
  readArr(br, bc, B);
  multArrs(ar, A, bc, B, ac, C);
  printResult(ar, C, bc);


}
//read in the matrix from the command line
void readArr(int r, int c, double **arr)
{
for (int i = 0; i < r; ++i) {
    for (int j = 0; j < c; ++j) {
        std::cin>> arr[i][j];
        cout << " \n" << arr[i][j];
    }
}
}

void multArrs(int ar, double **A, int bc, double **B, int br, double **C)
{
    for(int i=0; i<ar; ++i)
    for(int j=0; j<bc; ++j)
    for(int k=0; k<br; ++k)
    {
        C[i][j]+=A[i][k]*B[k][j];
    }
}

void printResult(int r1, double **C, int c1)
{
cout << endl << "Output Matrix: " << endl;
    for(int i=0; i<r1; ++i)
    for(int j=0; j<c1; ++j)
    {
        cout << " " << C[i][j];
        if(j==c1-1)
            cout << endl;
    }
}

程序使用以下命令运行:./matmult 3 3 3 3 &lt;matrix1 &lt;matrix2 它只会读取 matrix2 并将其放置在第一个双精度数组中,然后第二个双精度数组仅包含 0。矩阵文件如下所示:

2.0 3.0 1.0
6.0 2.0 2.0
7.0 3.0 5.0

感谢您提供的任何见解。我曾尝试寻找答案,但找不到答案。还必须使用 读取矩阵

【问题讨论】:

  • 你从哪里读取文件? readArr() 正在从 cin 读入
  • @NathanOliver cin 读入文件但它只读入一个文件
  • @SeanRyan 这是不正确的方法。将文件名作为参数传递并使用ifstream 读取文件。

标签: c++ matrix command-line command-line-arguments matrix-multiplication


【解决方案1】:

由于您为此使用了特定于 shell 的功能,因此这两个相互重定向,最好知道您使用的是什么操作系统和什么 shell。我会改为使用文件名作为参数并从程序中打开文件。

【讨论】:

    【解决方案2】:

    这样你只能传递一个输入文件,因为它是标准输入的重定向。所以这就是程序只读取第二个矩阵的原因,因为它只读取最后一条语句。请使用文件名作为参数并在源代码中打开文件或将两个文件合并为一个。

    【讨论】:

      猜你喜欢
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 2011-11-18
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      相关资源
      最近更新 更多