我正在阅读带有数字的文本文件,以便将它们存储在矩阵中:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
此代码适用于5x5矩阵,但如果我想要100x100矩阵,我是否必须写&matrix1[i][column]
100次?
有没有办法以更动态的形式这样做?
FILE *file;
file = fopen("origin.txt", "r");
if (file == NULL){
cout << "Error opening file" << endl;
}
int i = 0;
while (1){
if (feof(file))
break;
fscanf(file, "%d %d %d %d %d\n", &matrix1[i][0], &matrix1[i][1], &matrix1[i][2], &matrix1[i][3], &matrix1[i][4]);
i++;
}
编辑(回复@RemyLebeau):因为我从未使用过fstream,所以我一直在搜索它的使用示例,我找到了这个:
std::ofstream output("inputMatrix.txt");
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < numColumns; j++)
{
output << matrix1[i][j] << " ";
}
output << "\n";
}
但我不知道如何使用ifstream。你能给我一个如何使用ifstream的简单例子吗?
答案 0 :(得分:0)
首先,您必须决定在代码中支持哪种矩阵:只有方形矩阵或更通用的矩形矩阵。
假设你决定支持矩形矩阵。然后,文件中的前两个数字应指定矩阵的行数和列数,然后是实际数据,例如2x3矩阵可以这样描述。
2 3
1 2 3
4 5 6
其次,您必须决定如何在内存中表示矩阵。让我们假设您的课程至少包含以下成员:
class Matrix2d
{
public:
// create matrix of given size, filled with zeroes
Matrix2d(int numRows, int numCols);
// get reference to matrix element at given position
// we assume matrix elements are of type int
int& operator()(int row, int col);
}
然后读取矩阵将如下所示(无错误处理):
#include <fstream>
int main()
{
std::ifstream is("origin.txt");
int numRows, numCols;
is >> numRows >> numCols;
Matrix2d mat(numRows, numCols);
for (int i = 0; i < numRows; ++i)
for (int j = 0; j < numCols; ++j)
is >> mat(i, j);
return 0;
}
答案 1 :(得分:-2)
您可以这样使用:
ifstream file("origin.txt");
stringstream stream;
string str;
int i;
while (!file.eof()) {
getline(file,str);
stream.str(str);
while (stream >> i) {
cout << i << " ";
}
cout << endl;
stream.clear();
}