user3536870
user3536870

Reputation: 249

C++ array/matrix in a file

completely new to C++ and I have to use this programming language. And never done programming before.

Basically I need to read a matrix from a stored file so it's output can be seen when you press the debug button.

When I've tried doing the matrix

1 3 5

2 4 6

5 7 9

When I come to reading it, it comes up with the matrix but in a line so.... 1 3 5 2 4 6 5 7 9.

So does anybody know how to get it so it's read as a matrix, if that's possible?

In the future I then need to find the determinant of the matrix e.t.c. And do other sums between multiple matrices.

Here is what I currently have:

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

Upvotes: 0

Views: 140

Answers (1)

user3235832
user3235832

Reputation:

If you have an array of 9 numbers, you can read them in with an ifstream object

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();

Better still you can create a class / structure for your matrix and read it in using a member function, and add operators (such as the determinant).

EDIT:

If you just want to print the matrix in... matrix form, just use 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();

This does however assume you are actually format the data as a matrix.

Upvotes: 1

Related Questions