以下是我的代码的几个片段。首先是我写的函数。给我一个错误的是fileout函数,它应该将向量写入文件。
vector<int> random(int rowsize, int columnsize) // generates a random matrix given number of rows and columns, stores it as a 1-dimensional vector
{
int elements = rowsize*columnsize;
vector<int> x(elements);
int matrix[10][10];
int n=0;
for(int i = 0; i < rowsize; i++)
{
for(int j = 0; j < columnsize; j++)
{
matrix[i][j]= -10 + rand() % 21;
x[n++] = matrix[i][j];
}
}
return x;
}
void print(vector<int> matrix, int columnsize) //prints the matrix given the number of columns
{
for(int i=0; i < matrix.size(); i++)
{
if(i%columnsize != 0)
cout << setw(10) << matrix[i];
if(i%columnsize == 0)
cout << endl << setw(10) << matrix[i];
}
cout << endl;
}
vector<int> addmat(vector<int> matrixA, vector <int> matrixB) //adds two matrices together, takes vector input
{
vector<int> matrix(matrixA.size());
for(int i=0; i< matrixA.size(); i++)
matrix[i] = (matrixA[i] + matrixB[i]);
return matrix;
}
vector<int> filefill(ifstream &fin, string file, int rowsize, int columnsize) //creates a matrix from a file
{
fin.open(file.c_str());
vector<int> matrix;
int number;
for(int i=0; i < rowsize*columnsize; i++)
{
while(fin >> number)
matrix.push_back(number);
}
fin.close();
return matrix;
}
void fileout(ofstream fout, string file, vector<int> matrix) //writes a matrix onto a file
{
fout.open(file.c_str());
for(int i=0; i < matrix.size(); i++)
fout << matrix[i];
fout.close();
}
这是主要功能的使用。 fileout函数内的fout标记为错误:
&#34; 6 IntelliSense:&#34; std :: basic_ofstream&lt; _Elem,_Traits&gt; :: basic_ofstream(const std :: basic_ofstream&lt; _Elem,_Traits&gt; :: _ Myt&amp; _Right)[with _Elem = char, _Traits =标准:: char_traits]&#34; (在&#34的第1034行声明; C:\ Program Files(x86)\ Microsoft Visual Studio 11.0 \ VC \ include \ fstream&#34;)无法访问c:\ Users \ William \ Desktop \ C ++ \ Homework8 \ HW8 \ hw8.cpp 163 11 HW8
else if (answer == "N" || answer == "n")
{
matrixA = random (Arow, Acolumn);
cout << "Matrix A" << endl;
print(matrixA, Acolumn);
matrixB = random (Brow, Bcolumn);
cout << "Matrix B" << endl;
print(matrixB, Bcolumn);
cout << endl << "Matrix A + Matrix B =" << endl;
vector<int> matrixC = addmat (matrixA, matrixB);
print(matrixC, Acolumn);
for (int i = 0; i < matrixA.size(); i++)
{
matrixB.push_back(matrixA[i]);
}
string filo;
cin >> filo;
ofstream fout;
fileout(fout, filo, matrixB);
}
不确定是什么问题?????????????
答案 0 :(得分:0)
尝试在ofstream
内部创建本地fileout
,而不是接受调用ofstream fout
函数的fileout
对象:
void fileout(string file, vector<int> matrix) //writes a matrix onto a file
{
ofstream fout;
fout.open(file.c_str());
for(int i=0; i < matrix.size(); i++)
fout << matrix[i];
fout.close();
}