Mantracker
Mantracker

Reputation: 613

Simple file writing with ostream_iterator creates file, but doesn't write

I have a really simple code to create a text file called "Input.txt", and write to it using ostream_iterator:

using namespace std;


int main()
{
    ofstream os{ "Input.txt" }; 
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++)
    {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);

    system("PAUSE");
    return 0;
}

The code above creates a "Input.txt", but there is nothing written to it. Am I missing something really obvious and fundamental?

Upvotes: 0

Views: 85

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 597540

You are not flushing the stream to disk before calling system().

You can explicitly flush() or close() the stream:

int main() {
    ofstream os{ "Input.txt" };
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++) {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);

    os.close();

    system("PAUSE");
    return 0;
}

Or you can put scoping braces around the stream so it goes out of scope sooner.

int main() {
    {
    ofstream os{ "Input.txt" };
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++) {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);
    }

    system("PAUSE");
    return 0;
}

Upvotes: 1

Mantracker
Mantracker

Reputation: 613

I figured it out, it was because I had "System("PAUSE")" in the code, blocking the output stream going into the file. This is the working code:

int main()
{
    ofstream os{ "Input.txt" }; // output stream for file "to"
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++)
    {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);
    return 0;
}

Can't believe I missed this....

Upvotes: 0

Related Questions