-1

i'm trying to read from a file and the file only gave 1 2 3 4 but the output is 1 2 3 4 4

#include <iostream>
#include <fstream>

using namespace std;

//declare matrix
const int size=100;
typedef int matrix[size][size];
matrix matA;
matrix matB; 
matrix result;

int main()
{
    fstream read;
    read.open("matrix A.txt", ios::in);
    
    while(!read.eof())
    {
        int temp;
        read >> temp;
        cout << temp << endl;
    }
}

i already saved the integer in different .cpp file, and the assignment asked to read the matrix using different .cpp

  • correct output should be 1 2 3 4 – Ian Puang May 10 '22 at 18:45
  • 2
    `int temp; while(read >> temp;) { cout << temp << endl; }` – πάντα ῥεῖ May 10 '22 at 19:01
  • This doesn't address the question, but get in the habit of initializing objects with meaningful values rather than default-initializing them and immediately overwriting the default values. In this case that means changing `fstream read; read.open("matrix A.txt", ios::in);` to `fstream read("matrix A.txt", ios::in);`. Even better, use an input stream: `ifstream read("matrix A.txt");`. – Pete Becker May 10 '22 at 19:12
  • 1
    @πάνταῥεῖ the `;` inside the `while` condition is wrong – Remy Lebeau May 10 '22 at 19:51

0 Answers0