将两个尺寸未知的文本文件中的两个矩阵相乘

Multiplying two matrices from two text files with unknown dimensions

本文关键字:两个 未知 文本 文件      更新时间:2023-10-16

这是我在这里的第一篇文章。我已经研究这个c++问题有一段时间了,但一无所获。也许你们可以给我一些提示,让我开始。

我的程序必须读取两个.txt文件,每个文件包含一个矩阵。然后,它必须将它们相乘,并将其输出到另一个.txt文件中。不过,我在这里的困惑是如何设置.txt文件以及如何获取尺寸。下面是矩阵1.text.的一个例子

#ivalue      #jvalue      value
   1            1           1.0
   2            2           1

矩阵的尺寸为2x2。

1.0     0
0       1

在开始乘以这些矩阵之前,我需要从文本文件中获得I和j的值。我发现的唯一方法是

int main()
{
  ifstream file("a.txt");
  int numcol;
  float col;
  for(int x=0; x<3;x++)
  {
    file>>col;
    cout<<col;
    if(x==1)     //grabs the number of columns
    numcol=col;
  }
  cout<<numcol;
}

问题是我不知道如何到达第二行来读取行数。除此之外,我不认为这会给我其他矩阵文件的准确结果。

如果有什么不清楚的地方,请告诉我。

更新谢谢我得到了正确工作的线索。但现在我遇到了另一个问题。在矩阵B中,设置为:

#ivalue      #jvalue         Value
    1         1              0.1
    1         2              0.2
    2         1              0.3
    2         2              0.4

我需要让程序知道它需要下降4行,甚至更多(矩阵维度未知。我的矩阵B示例是2x2,但它可能是20x20)。我有一个while(!file.of())循环我的程序,让它循环到文件末尾。我知道我需要一个动态数组来相乘,但这里也需要一个吗?

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    ifstream file("a.txt");      //reads matrix A
    while(!file.eof())
    {
        int temp;
        int numcol;
        string numrow;
        float row;
        float col;
        for(int x=0; x<3;x++)
        {
            file>>col;
            if(x==1)
            {
                numcol=col;      //number of columns
            }
        }
        string test;
        getline(file, test);     //next line to get rows
        for(int x=0; x<3; x++)
        {
            file>>test;
            if(x==1)
            {
                numrow=test;     //sets number of rows
            }
        }
        cout<<numrow;
        cout<<numcol<<endl;
    }

    ifstream file1("b.txt");     //reads matrix 2
    while(!file1.eof())
    {
        int temp1;
        int numcol1;
        string numrow1;
        float row1;
        float col1;
        for(int x=0; x<2;x++)
        {
            file1>>col1;
            if(x==1)
                numcol1=col1;    //sets number of columns
        }
        string test1;
        getline(file1, test1);   //In matrix B there are four rows.
        getline(file1, test1);   //These getlines go down a row.
        getline(file1, test1);   //Need help here.
        for(int x=0; x<2; x++)
        {
            file1>>test1;
            if(x==1)
                numrow1=test1;
        }
        cout<<numrow1;
        cout<<numcol1<<endl;
    }
}

"问题是我不知道如何到达第二行读取行数。"

使用std::getline到达下一行。

std::string first_line;
std::getline( file, first_line );