Skip to main content
Replace std::endl with newline
Source Link
Toby Speight
  • 88.3k
  • 14
  • 104
  • 327

You also need to check that the write operations (<<) succeeded. So instead of checking is_open(), just go through the whole series of operations, and check failbit at the end:

bool save_data() const
{
    std::ofstream saveFile(m_filename);

    saveFile << m_member1 << std::endl'\n'
             << m_member2 << std::endl;'\n';

    saveFile.close(); // may set failbit

    return saveFile;
}

Also, unless there's a pressing need to flush each line as it's written, prefer to use '\n' rather than std::endl (as I've shown), and let close() write it all in one go - that can make a significant difference to the speed, particularly when there's a large number of lines to be written.

You also need to check that the write operations (<<) succeeded. So instead of checking is_open(), just go through the whole series of operations, and check failbit at the end:

bool save_data() const
{
    std::ofstream saveFile(m_filename);

    saveFile << m_member1 << std::endl
             << m_member2 << std::endl;

    saveFile.close(); // may set failbit

    return saveFile;
}

You also need to check that the write operations (<<) succeeded. So instead of checking is_open(), just go through the whole series of operations, and check failbit at the end:

bool save_data() const
{
    std::ofstream saveFile(m_filename);

    saveFile << m_member1 << '\n'
             << m_member2 << '\n';

    saveFile.close(); // may set failbit

    return saveFile;
}

Also, unless there's a pressing need to flush each line as it's written, prefer to use '\n' rather than std::endl (as I've shown), and let close() write it all in one go - that can make a significant difference to the speed, particularly when there's a large number of lines to be written.

Source Link
Toby Speight
  • 88.3k
  • 14
  • 104
  • 327

You also need to check that the write operations (<<) succeeded. So instead of checking is_open(), just go through the whole series of operations, and check failbit at the end:

bool save_data() const
{
    std::ofstream saveFile(m_filename);

    saveFile << m_member1 << std::endl
             << m_member2 << std::endl;

    saveFile.close(); // may set failbit

    return saveFile;
}