2014-04-28 122 views
0

嘗試將矩陣寫入文件時出現問題。我設法打開一個文本文件,而不是顯示一個3x3矩陣,這是一個很長的數字,這是一個錯誤。將矩陣寫入文件

我的代碼是

outf.open("Out2.txt"); 
      cout<<"Please enter the output file(Out2.txt\n"; 
      cin>>outfile; 
      if (outfile == "Out2.txt"); 
      {          
      outf<<"The sum of Matrix X and Matrix Y is:"<<sum[3][3]; 
       }    
      outf.close(); 

可能的解決方案很瑣碎,但我一直沒能在網上找到解決方案!

+0

可能是你在網上搜索如何寫在文件矩陣,而不是搜索如何寫2D或3D陣列到文件。 –

回答

2

你需要寫出來的矩陣元素單獨

out << sum[0][0] << "," << sum[0][1] << etc. 
+2

也從'if'結尾刪除分號 – vsoftco

0

outf<<"The sum of Matrix X and Matrix Y is:"<<sum[3][3]; 

寫入文件的蜂窩小區中的4號線和4列的內容。

正如大衛說賽克斯,你應該重複寫的所有單元格:

for(int lin=0;line<nb_lines;lin++) 
{ 
    for(int col=0;col<max_col;col++) 
    { 
     ouf << sum[lin][col] << " " ; 
    } 
    ouf << std::endl ; 
}