How do you add a new line to a c++ string? I'm trying to read a file but when I try to append '\n' it doesn't work.
std::string m_strFileData;
while( DataBegin != DataEnd ) {
m_strFileData += *DataBegin;
m_strFileData += '\n';
DataBegin++;
}
The newline character ( \n ) is called an escape sequence, and it forces the cursor to change its position to the beginning of the next line on the screen. This results in a new line.
Adding Newline Characters in a String In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.
You can just add the \n character to the string to create a new line.
The printf statement does not automatically append a newline to its output. It outputs only what the format string specifies. So if a newline is needed, you must include one in the format string. The output separator variables OFS and ORS have no effect on printf statements.
If you have a lot of lines to process, using stringstream
could be more efficient.
ostringstream lines;
lines << "Line 1" << endl;
lines << "Line 2" << endl;
cout << lines.str(); // .str() is a string
Output:
Line 1
Line 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With