【发布时间】:2018-05-13 14:26:16
【问题描述】:
我有一个名为 matrices.txt 的文件,其中包含两个 3 x 3 的矩阵。 它们是:
1 2 3
4 5 6
7 8 9
1 2 3
4 5 6
7 8 9
我正在尝试从该文件中读取数据并将其存储到数组 proto_matrix 中,以便稍后将其拆分为两个矩阵。
我遇到的问题是我无法将数字存储在数组中。
我的代码是
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
int i = 0, j, k = 0, n, dimension;
cout << "Enter the dimension of square matrices (3 by 3 would be 3) \n";
cin >> n;
dimension = n * n;
int proto_matrix[2 * dimension];
// make array of two matrices combined, this will be split into two matrices
ifstream matrix_file("matrices.txt");
while(matrix_file)
{
matrix_file >> proto_matrix[i];
}
matrix_file.close();
}
我尝试调试代码,似乎没有整数存储在数组中,只是随机数。
【问题讨论】:
-
int proto_matrix[2 * dimension];不是标准 C++;您必须为2 * dimensionints 动态分配足够的内存。 -
在阅读之前务必确保文件
is_open()。 -
试一试
while(matrix_file >> proto_matrix[i];) { i++; }。您没有在读取时增加i,因此读取的所有值(如果有)都进入了数组中的同一插槽,并且您想在计数之前测试读取是否成功。 -
使用
std::vector<int> proto_matrix(2 * dimensions);而不是您正在使用的非标准 C++ 语法。 -
顺便说一句,
main函数返回int。总是。
标签: c++ arrays file loops matrix