Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't add a new line to c++ string

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++;
}
like image 200
Will Avatar asked Nov 08 '10 21:11

Will


People also ask

How do I add a new line in C?

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.

Can you put \n in a string?

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.

How do I add a line to a string in C++?

You can just add the \n character to the string to create a new line.

How do I add a new line in printf?

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.


1 Answers

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
like image 70
Steve Townsend Avatar answered Oct 06 '22 00:10

Steve Townsend