【问题标题】:C++ array/matrix in a file文件中的 C++ 数组/矩阵
【发布时间】:2014-04-15 16:35:44
【问题描述】:

对 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;
}

【问题讨论】:

标签: c++ arrays matrix


【解决方案1】:

如果您有一个由 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();

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

【讨论】:

  • 嗯,我刚试过,但没用。可能是对的,我只是不知道自己在做什么。嗯:(
  • @user3536870 为什么它不起作用?您是否收到运行时/编译器错误,或者数字读取不正确?
  • 黑匣子打开后又立即关闭,打开的半秒空白
  • @user3536870 从您的代码中看起来好像程序以EXIT_FAILURE 标志关闭。检查您正在打开的文件是否存在并且在正确的目录中。
  • @user3536870 顺便说一句,“黑盒子”被称为 控制台 :)
猜你喜欢
  • 2017-08-03
  • 2016-06-09
  • 2012-02-18
  • 2013-03-13
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 2021-03-04
  • 1970-01-01
相关资源
最近更新 更多