C++ New line character when outputting to a text file [closed]

烈酒焚心 提交于 2019-12-12 16:53:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!