std::endl in a string variable?

你离开我真会死。 提交于 2019-12-02 00:12:19

问题


Hi i want to save multiply lines in a string. I got a string logstring and i want to save multiplay error logs which i later can print in a txt file or as a console output. Is there a possibility to use endl to format a string variable? I searched the internet but i only find

cout << "" << endl;

Now my idea was:

std::string logstring;
logstring = logstring + "Error Message" + "Number" + "Time + Date";
logstring += endl;

Is something like this possible or is there no way to format string variables? Later i want to print them to a log.txt file? Is it possible to use a string like this?

std::ofstream logfile;
logfile.open(log.txt);
logfile << logstring;

The text file should look like this

Error Message 1 Date
Error Message 2 Date
Error Message 3 Date
...

Is it possibly to get it like this or do i have to print all lines seperatly?


回答1:


Don't forget std::endl adds a new line and flushes the buffer.

If you simply want new lines, \n, add them to your string, using + or stream them to a stream, using << '\n'.

For example,

std::string logstring;
logstring = logstring + "Error Message" + "Number" + "Time + Date";
logstring += '\n';



回答2:


It's not possible. Use logstring += "\n"; instead




回答3:


std::endl isn't only a \n (newline) character, but it also flushes the stream.

If you have a file open in 'text-mode', your operating system should replace \n with the correct platform specific end of line character(sequence). So simply appending a \n should be fine. Portable end of line (newline)

Also note that by default, standard input and output are opened in textmode with msvc.




回答4:


To separate lines in a string you should use the new line escape character '\n'.

For example

std::string logstring;

//...

logstring += "Error Message 1 Date";
logstring += '\n';

logstring += "Error Message 2 Date";
logstring += '\n';

logstring += "Error Message 3 Date";
logstring += '\n';

As for std::endl then it is a function declared like

template <class charT, class traits>
basic_ostream<charT, traits>& endl(basic_ostream<charT, traits>& os);

It is a so-called stream manipulator. Fo example in this statement

std::cout << std::endl;

there is used operator << that accepts pointer to the function as an argument.

You can not concatenate a string with the function pointer std::endl and if you did this somehow it did not make sense.



来源:https://stackoverflow.com/questions/44628741/stdendl-in-a-string-variable

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