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

隐身守侯 提交于 2019-12-10 17:22:35

问题


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++;
}

回答1:


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



回答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).




回答3:


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.




回答4:


Just a guess, but perhaps you should change the character to a string:

 m_strFileData += '\n';

to be this:

 m_strFileData += "\n";



回答5:


Try this:

ifstream inFile;
inFile.open(filename);
std::string entireString = "";
std::string line;

while (getline(inFile,line))
{
   entireString.append(line);
   entireString.append("\n");
}


来源:https://stackoverflow.com/questions/4128077/i-cant-add-a-new-line-to-c-string

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