1

I'm writing a program that print an array to a text file, then read that array from that text file to another array, this is my program:

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

void PrintToFile(int arr[], ofstream& PrintFile)
{
    for (int i = 0; i < 10; i++) 
    {
        arr[i] = i;
        PrintFile << arr[i] << " ";
    }
}

void ReadFromFile(int arr[], ifstream& ReadFile)
{
    for (int i = 0; i < 10; i++)
        ReadFile >> arr[i];
}

int main()
{
    int arr1[10];
    int arr2[10];

    ofstream PrintFile("output.txt");
    ifstream ReadFile("output.txt");

    PrintToFile(arr1, PrintFile);
    ReadFromFile(arr2, ReadFile);

    for (int i = 0; i < 10; i++)
        cout << arr1[i] << " ";

    cout << endl;

    for (int i = 0; i < 10; i++)
        cout << arr2[i] << " ";
}

This is the output for the program:

0 1 2 3 4 5 6 7 8 9
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460

I don't understand why it printed out those number for the second array, it suppose to be the same as the first array, can someone help me with this? Thanks for your help!

2
  • You cannot have 2 handles open to a single file. All your reads failed, because ReadFile.is_open() is false. Commented Aug 16, 2021 at 12:35
  • In C++, the responsibility for detecting problems is on the developer's shoulders. This code does not check to see if the files were opened. It also does not check to see if reading fails. Running with scissors, blindfolded. Commented Aug 16, 2021 at 12:57

2 Answers 2

1

You can only open a file once, so all your reads fail and the array is left with indeterminate values.

While you can open for both reading and writing at once, it's more common (and has fewer surprises) to close after writing and only then open for reading.

This should work:

ofstream PrintFile("output.txt");
PrintToFile(arr1, PrintFile);
PrintFile.close();
ifstream ReadFile("output.txt");
ReadFromFile(arr2, ReadFile);

or, you could use a separate scope to delimit the writing stream's life and make it impossible to forget about closing:

{
    ofstream PrintFile("output.txt");
    PrintToFile(arr1, PrintFile);
}
ifstream ReadFile("output.txt");
ReadFromFile(arr2, ReadFile);
Sign up to request clarification or add additional context in comments.

Comments

0

Just close the PrintFile after PrintToFile(), before the next operation of ReadFromFile().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.