问题
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. :)
回答1:
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.
回答2:
In your writeEol()
method, you output both a newline (\n
), and you write out a std::endl
. These both have the effect of writing out a newline, which is what you want. However, the std::endl
will also flush the stream, which in some cases is not desireable (it could cause slowdown if the stream is flushed after every line).
I think that your code will do what you want (albeit with two newlines), but as shuttle87 states, you only need a \n
at the end of each line to achieve the desired affect.
来源:https://stackoverflow.com/questions/13415833/c-new-line-character-when-outputting-to-a-text-file