繁体   English   中英

文件中的C ++数组/矩阵

[英]C++ array/matrix in a file

完全是C ++的新手,我必须使用这种编程语言。 从来没有做过编程。

基本上,我需要从存储的文件中读取一个矩阵,以便在按下调试按钮时可以看到其输出。

当我尝试做矩阵

1 3 5

2 4 6

5 7 9

当我阅读它时,它与矩阵一起出现,但是排成一行。...1 3 5 2 4 6 5 7 9。

那么,如果可能的话,有人知道如何获取它,使其作为矩阵读取吗?

将来我需要找到矩阵的行列式等,并在多个矩阵之间进行其他求和。

这是我目前拥有的:

#include <iostream>
#include <conio.h>
#include <cmath>
#include <fstream>
#include <cstdlib>

using namespace std; 

int main()
{
    char filename[50];
    ifstream matrixA;
    cin.getline(filename, 50);
    matrixA.open(filename);

    if (!matrixA. is_open())
    {
        exit (EXIT_FAILURE);
    }
    char word[50];
    matrixA >> word;
    while (matrixA.good())
    {
        cout << word << " ";
        matrixA >> word;
    }
    system("pause");
    return 0;
}

如果您有9个数字组成的数组,则可以使用ifstream对象读取它们

float elements[9];

ifstream reader(/*your file*/);

reader >> elements[0] >> elements[1] >> elements[2]; //read first line
reader >> elements[3] >> elements[4] >> elements[5]; //read second line
reader >> elements[6] >> elements[7] >> elements[8]; //read third line

reader.close();

更好的是,您可以为矩阵创建一个类/结构,并使用成员函数读取该类/结构,并添加运算符(例如行列式)。

编辑:

如果只想以...矩阵形式打印矩阵,则使用std::getline ;

ifstream reader(/*your file*/);

char buffer[300];

//1st line
std::getline(reader, buffer);
cout << buffer << endl;

//2nd line
std::getline(reader, buffer);
cout << buffer << endl;

//3nd line
std::getline(reader, buffer);
cout << buffer << endl;

reader.close();

但是,这确实假定您实际上是将数据格式化为矩阵。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM