c++ - 我的 C++ 程序不会从命令行读取多个文件

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

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

#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 <matrix1 <matrix2 它只会读入 matrix2 并将其放在第一个 double 组中,然后第二个 double 组只包含 0。矩阵文件如下所示:

2.0 3.0 1.0
6.0 2.0 2.0
7.0 3.0 5.0

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

最佳答案

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

关于c++ - 我的 C++ 程序不会从命令行读取多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32822208/

相关文章:

c++ - C++ 中的 move 语义是否缺少 C 所缺少的东西?

c++ - OpenCV2 编解码器支持

python - 矩阵除以另一个矩阵的行,在 theano 中没有循环

windows - 命令 "date+%s"在 Windows 中的等效项是什么

python - 当类没有继承任何内容时,从命令行调用 python 脚本会出现语法错误,这是为什么?

c++ - 类模板中的转换运算符

c++ - C++语言中cin函数的问题

python - 二体轨道建模问题

python - 减少行梯队表单脚本在特定情况下不起作用

command-line - X11:通过命令行设置未装饰或始终可见的窗口