C++ New line character when outputting to a text file

51,497

Without a proper question I can just guess what you're trying to learn, so feel free to update your "question" with an actual question:

You're essentially writing two line breaks into the file, depending on the encoding (i.e. Windows or Unix line breaks) you won't see the difference:

std::endl will automatically include the correct character to create a linebreak. There's no need to write "\n" as well.

Also you don't have to pass std::endl to the stream unless you really want a line break at the specific position:

std::cout << "The result is: ";
std::cout << 50 << std::endl;

Keep in mind that depending on your editor you might not see all line breaks, e.g. Windows Notepad won't show a line break with only \n. It will instead appear as an invisible character. For actual line breaks that are accepted you'd beed \r\n. In comparison, the Open Source editor Notepad++ accepts and displays both kinds of line breaks.

Share:
51,497
James Warner
Author by

James Warner

Updated on November 17, 2020

Comments

  • James Warner
    James Warner over 3 years

    This is just a quick question. But I am trying to output data to a file, which works fine. However I am also trying to implement a new line at the appropriate point so the data, prints on individual lines.

    This is how my code currently looks:

    main.cpp

    Writer w("Output.txt");
        w.writeString("The number of words in the script are: ");
        w.writeInt(count);
        w.writeEol();
        w.writeString("The number of Officers in the script are: ");
        w.writeInt(ofCount);
        w.writeEol();
        w.writeString("The number of Courtiers in the script are: ");
        w.writeInt(cCount);
            w.close();
    

    Writer.cpp

    void Writer::writeEol()
    {
        out << "\n" << endl;
    }
    

    My code has to be implemented this way as my whole system is built around it like this.

    So my question is, how would I adjust my Writer::writeEol() to add a new line to my output file?

    My output file currently comes out like this:

        The number of words in the script are: 32339The number of Officers in the script are: 2The number of Courtiers in the script are: 9
    

    Any help is greatly appreciated. :)