1

我正在使用 scanf() 函数将矩阵分配给变量,但我想从文本文件中调用矩阵。

这是我的代码:

  int rows;
  int columns;
  float weight;
  float step;

  printf("Enter the number of rows and columns of the matrix.\n");
  scanf("%d%d", &rows,&columns);

  printf("Enter step for the weight.\n");
  scanf("%f", &step);

  int a[rows][columns], b[rows][columns],i,j;
  float c[rows][columns];

  printf("Enter the First matrix->");
  for(i=0;i<rows;i++)
      for(j=0;j<columns;j++)
           scanf("%d",&a[i][j]);
  printf("\nEnter the Second matrix->");
  for(i=0;i<rows;i++)
      for(j=0;j<columns;j++)
           scanf("%d",&b[i][j]);
4

1 回答 1

5

2个可能的解决方案:

1)您可以保留您的代码而无需修改。然后你必须以这种方式调用你的二进制程序:

$ myprogram < myfile.txt

在此解决方案中,标准输入流将被myfile.txt文件流替换。

2)使用fscanf()从文件中读取而不是使用scanf()从标准输入读取

于 2013-06-18T16:15:22.147 回答