2012-09-08 35 views
2

这是我第一篇文章。我一直在研究这个C++的问题一段时间了,并没有得到任何帮助。也许你们可以给我一些提示让我开始。从两个未知尺寸的文本文件中乘以两个矩阵

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

#ivalue  #jvalue  value 
    1   1   1.0 
    2   2   1 

矩阵的维数是2×2。

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; 
} 

的问题是我不知道怎么去第二线读取的行数。最重要的是,我不认为这会为我提供其他矩阵文件的准确结果。

让我知道是否有什么不清楚。

UPDATE 谢谢! 我得到了getline正常工作。但是现在我遇到了另一个问题。在矩阵B是设置这样的:。

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

我需要让程序知道它需要往下走4号线,甚至更多(矩阵尺寸是未知的我的矩阵B的例子是一个2×2,但它可能是20x20)。我有一段时间(!file.eof())循环我的程序,让它循环直到文件结束。我知道我需要一个动态数组进行乘法运算,但是在这里我还需要一个数组吗?

#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; 
    } 
} 
+0

您是否熟悉STL容器?你如何在内存中表示矩阵? – Beta

回答

0

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

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

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