我正在大学做一个实验室,它从2个不同的文件中抽出2个矩阵,并且在我被要求在控制台上打印结果的一个问题中(这不是问题,已经完成)但是将其打印到新的保存文件是个问题。
我对c ++很新,所以如果错误显而易见,我会事先道歉:(
这是我到目前为止的代码......
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
///////// my output file /////////////
string outfile1, save;
cout<<"Please enter the name of the file you want to save the results in"<<endl;
cin>>outfile1;
ofstream outfile(outfile1.c_str());
if(!outfile)
{
cout<<"Please drag in the right file you want the results to be saved on"<<endl;
system("PAUSE");
return -1;
}
/////// sitting up the first matrix file ////////
string matrixA;
cout<< "Please drag file (matrix1) into this window"<<endl;
cin>>matrixA;
ifstream infile;
infile.open(matrixA.c_str());
if(!infile)
{
cout<<"ERROR: Wrong file, please try restart program and try again."<<endl;
return -1;
}
string matrix1;
int a[5][5];
for (int i = 0; i<5;i++)
{
for(int j = 0;j<5;j++)
{
getline(infile,matrix1,',');
a[i][j]= stoi(matrix1);
cout<< a[i][j]<<" ";
}
cout<<endl;
}
infile.close();
/////// sitting up the 2nd matrix file ////////
string matrixB;
cout<< "Please drag file (matrix2) into this window"<<endl;
cin>>matrixB;
ifstream infile2;
infile2.open(matrixB.c_str());
if(!infile2)
{
cout<<"ERROR: Wrong file, please try restart program and try again."<<endl;
return -1;
}
string matrix2;
int b[5][5];
for (int k = 0; k<5;k++)
{
for(int l = 0;l<5;l++)
{
getline(infile2,matrix2,',');
b[k][l]= stoi(matrix2);
cout<< b[k][l]<<" ";
}
cout<<endl;
}
infile2.close();
////////////// CALCULATIONS //////////////////////
cout<<"The product of both matrices is: "<<endl;
int result[5][5];
while (outfile1)
for (int x = 0; x < 5; x++)
{
for (int y = 0; y < 5; y++)
{
result[x][y] = 0;
for(int z = 0; z < 5; z++)
{
result[x][y] += a[x][z]*b[z][y];
}
cout << result[x][y] <<" ";
outfile1<< result[x][y]<<" "; // <<---------- why can i not do this?
}
cout<<endl;
}
system("PAUSE");
return 0;
}
有更简单的方法吗?如果我尝试按原样运行代码,它会在第一个“&lt;&lt;”下给我一个亮点说(没有运算符“&lt;&lt;”匹配这些操作数)
outfile1<<result[x][y]<<" ";
答案 0 :(得分:1)
由于两个原因,您的程序无法编译。
while (outfile1)
outfile1
是std::string
(输出文件名),不能转换为bool
。您尝试使用此代码实现的目标并不十分清楚。
outfile1<< result[x][y]<<" ";
同样,outfile1
是std::string
。您的输出流为outfile
,因此您应将其更改为
outfile << result[x][y] << " ";
答案 1 :(得分:0)
outfile1
的类型为字符串,而outfile
的类型为ofstream。在第86行和第100行将outfile1
更改为outfile
,它应按预期进行编译。
您可能希望以不同方式命名变量以帮助防止此类错误,或者将outfile1
命名为outfileName
。