Anna
Anna

Reputation: 83

How to read a table from .txt file to C++

I want to read a matrix from a file and use it in my program. but when I output the results, it shows that it is not reading correctly. Here is the code:

#define I 5 
#define J 5 
#define P 2 

int i,j,k;  //for loops

int main ()
{
    ifstream inFile;
    ofstream outFile;
    double C[I][J];

    inFile.open("C.txt", ios::in);
    if (! inFile) {
        cerr << "unable to open file C.txt for reading" << endl;
        return 1;
    }

    for(i=0; i<I; i++)
        for(j=0; j<J; j++)
            inFile >> C[i][j];

    outFile.open("results.txt");
    outFile<< "C" <<endl;
    for(i=0;i<I;i++)
    {
        for(j=0;j<J;j++)
            outFile<< C[i][j];
        outFile<< endl;
    }

    inFile.close();
    outFile.close();

    return 0;
}

C is a matrix of integer values 2 3 5... but what I get is

316-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061

Upvotes: 3

Views: 12597

Answers (3)

netcoder
netcoder

Reputation: 67745

It seems you are writing uninitialized variables to your output file, leading to undefined behavior.

I suspect your C.txt file does not contain the 5x5 matrix your program is looking for.

You should add a simple error check, e.g.:

for(i=0; i<I; i++)
    for(j=0; j<J; j++)
        if (!(inFile >> C[i][j])) { /* something's wrong here */ }

Upvotes: 2

n. m. could be an AI
n. m. could be an AI

Reputation: 120079

You should output a whitespace after each number, otherwise they will be all glued together.

outFile<< C[i][j] << " ";

You also should check your input for validity. Not showing it here (you already know how to check if (! inFile)).

Upvotes: 3

marcinj
marcinj

Reputation: 50036

I suspect that you are having problems with new lines, below modification will ignore new line character after reading each line:

for(i=0; i<I; i++) {
    for(j=0; j<J; j++)
        inFile >> C[i][j];
    inFile.ignore();  /// <<<--------
}

Upvotes: 2

Related Questions