Search code examples
c++fstreamiostream

Output for the matrix A is overlapped with the Matrix B


So,this is a code for reading matrix A and B from txt files. The following code that i found was able to read both files. However, the output for the matrix A is overlapped with the Matrix B (picture below) enter image description here

Matrix A -----
1       2       3
4       5       6
7       8       99 

Matrix B -----
0       1       1
2       0       0
2       0       00 

So, how to avoid it overlapping, please help :)

#include<iostream>
#include<fstream>
using namespace std;

int main()
{

    {   
        char ch;
        const char *fileName="MatrixA.txt";     // FOR MATRIX A

        ifstream file;

            file.open(fileName,ios::in);
                if(!file)
                {
                    cout<<"Error in opening file!!!"<<endl;
                    return -1; 
                }


                while (!file.eof()) 
                {
                    file >> noskipws >> ch; 
                    cout << ch; 
                }

        file.close();
    }

    {
        char ch;
        const char *fileName="MatrixB.txt";     // FOR MATRIX A

        ifstream file;

            file.open(fileName,ios::in);
                if(!file)
                {
                    cout<<"Error in opening file!!!"<<endl;
                    return -1; 
                }


                while (!file.eof()) 
                {
                    file >> noskipws >> ch; 
                    cout << ch; 
                }

        file.close();
    }


    return 0;
}

EDIT: Thanks everyone! Fixed it and yes i know that this is not a code for reading matrices (sorry for the misinformation). i just want it to look like one hehe so thanks again


Solution

  • You've just printed a character-by-character copy of the two files, with nothing between them. Apparently "MatrixA.txt" does not have a newline at the end of the file.

    You can just add a '\n' character after the output of the first file.

    std::cout << '\n';
    

    In a very real sense you have not read in two matrices, as you don't utilise any arithmetic values present in the files. If you want to do that, you will first have to come up with some representation of a Matrix in your program, and only then can you think about reading it from your files.