如何从C++文件中读取矩阵
How to read in a matrix from a file in C++?
>我试图从文件中读取n×n个矩阵,然后将该矩阵存储在一维数组中。我还想存储 n 的值。我已经研究了各种方法,但似乎无法将它们应用于我想要实现的目标。
这就是我到目前为止所拥有的,但我不确定该在 while 循环中放入什么。
/*READ IN THE IMAGE MATRIX FROM THE FILE*/
String lineA;
ifstream imFile;
imFile.open("imageMatrixDefined.txt");
if(imFile.fail()){
cerr << "File cannot be found or opened" << endl;
exit(1);
}
if(imFile.is_open(){
cout << "file opened successfully!" << endl;
while(!imFile.eof()){
}
}
输入文件可能如下所示:
1 2 3
2 3 1
3 3 2
其中制表符分隔元素。任何建议将不胜感激,因为我是C++新手。
数组具有固定大小。
在初始化数组之前,必须先获取 n 的值。
最好仔细检查是否要将该矩阵存储在一维数组或二维数组中。 如果是一维数组,检查矩阵在一维数组中的存储方式是好的。 有些存储它的第一行、第二行、...和第n行,有些存储它的第一列、第二列、...和第n列。
矩阵为 n × n,因此列数等于行数。
该文件一次存储一行。获取 n 的值并不困难。
至关重要,但在 while 循环之前,获取 n 的值是解决问题的第一步。
当得到 n 的值时,数组很容易被初始化。您可以从 while 循环中的文件中逐一读取该行,使用分隔符作为制表符来获取每个矩阵元素,并将矩阵元素存储在数组中。
将 2D 数组读取到文件。假定输入以逗号分隔,每行一行,每行 x 列数,每列由制表符 (t
) 字符分隔。不需要 EOL(行尾)选项卡,只需换行符 ( n
)。请记住正确设置rows
和columns
变量。测试代码是否正常工作。
using namespace std;
#include <iostream>
#include <fstream>
int main() {
int rows=10, columns=10;
ifstream f("input.txt");
int input[rows][columns];
for (int i=0; i<rows; i++){
for (int j=0; j<columns; j++){
f >> input[i][j];
}
}
f.close();
// Here you can add processing of the file, for example, print it:
cout << "Input:" << endl;
for (int i=0; i<rows; i++){
for (int j=0; j<columns; j++){
cout << input[i][j] << " ";
}
cout << endl;
}
return 0;
}
您必须将自定义输入流与输入文件绑定。假设您的输入文件是"in.txt",它看起来与您指定的相同。
然后,以下代码从文件中读取,将其存储在一维数组中,并以矩阵形式打印生成的矩阵:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream myfile;
myfile.open ("in.txt");
cout << "Reading from a file.n";
int arr[10];
int k = 0;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
myfile >> arr[k]; //Read it in a 1D array
cout << arr[k] << " ";
++k;
}
cout << "n";
}
myfile.close();
return 0;
}
输出:
Reading from a file.
1 2 3
2 3 1
3 3 2
相关文章:
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 读取文件的最后一行并输入到链接列表时出错
- 为什么在读取文件大小时文件IO速度会发生变化
- 读取文件时运行时的未知行为
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C++ 读取文件读取文件不正确
- 读取文件并将其存储在unordered_map中时出现问题
- 读取文件时无法使用 OpenMP 获得加速
- 使用istringstearm和get行缓慢读取文件
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 读取文件时引发异常
- 从标准输入读取文件后读取用户输入
- 在读取文件后重置句柄
- 如何在C++编译时读取文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 读取文件在第二次调用时返回INVALID_HANDLE
- 通过指针读取文件
- 逐行读取文件,并将数据插入变量和数组中