Question

Basic question I'm hoping theres a way to solve. When I write to a file in my c++ with ofstream it adds a blank line at the end. Is there anyway to stop this behavior? It is causing issues when I load the file the next time the program is run.

int saveScores(scoreboard sBoard, const string filename) {
    ofstream outStream;
    outStream.open("/Users/Wescat/Desktop/Programming/comp2710/wsc0010_project1/scores.txt");
    if (outStream.fail()) {
        cout << "Output file opening failed." << endl;
        return 1;
    }
    int i = 0;
    while (i < sBoard.numOfScores) {
        outStream << sBoard.score->name << endl;
        outStream << sBoard.score->score << endl;

        sBoard.score = sBoard.score->next;
        i++;
    }
    outStream.close();
    return 0;
}
Was it helpful?

Solution

This is perfectly reasonable.

What you're interpreting as a blank line is just the way your text editor represents the presence of a \n character at the end of your actual final line (generated by your final std::endl). It makes sense for that character to be there, as it is as the end of all of your lines. Indeed, this is what "line ending" means!

If this is causing problems when you load the file back in, then I'd suggest that your real bug is in fact there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top