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( D开发者_JS百科ataBegin != DataEnd ) {
m_strFileData += *DataBegin;
m_strFileData += '\n';
DataBegin++;
}
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
Sorry about the late answer, but I had a similar problem until I realised that the Visual Studio 2010 char*
visualiser ignores \r
and \n
characters. They are completely ommitted from it.
Note: By visualiser I mean what you see when you hover over a char*
(or string
).
Just a guess, but perhaps you should change the character to a string:
m_strFileData += '\n';
to be this:
m_strFileData += "\n";
This would append a newline after each character, or string depending on what type DataBegin actually is. Your problem does not lie in you given code example. It would be more useful if you give your expected and actual results, and the datatypes of the variables use.
Try this:
ifstream inFile;
inFile.open(filename);
std::string entireString = "";
std::string line;
while (getline(inFile,line))
{
entireString.append(line);
entireString.append("\n");
}
精彩评论