我无法在 C++ 字符串中添加新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4128077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I can't add a new line to c++ string
提问by Will
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.
如何在 C++ 字符串中添加新行?我正在尝试读取文件,但是当我尝试附加 '\n' 时,它不起作用。
std::string m_strFileData;
while( DataBegin != DataEnd ) {
m_strFileData += *DataBegin;
m_strFileData += '\n';
DataBegin++;
}
回答by Steve Townsend
If you have a lot of lines to process, using stringstream
could be more efficient.
如果您有很多行要处理,使用stringstream
可能会更有效。
ostringstream lines;
lines << "Line 1" << endl;
lines << "Line 2" << endl;
cout << lines.str(); // .str() is a string
Output:
输出:
Line 1
Line 2
回答by Harold Bamford
Just a guess, but perhaps you should change the character to a string:
只是猜测,但也许您应该将字符更改为字符串:
m_strFileData += '\n';
to be this:
是这样的:
m_strFileData += "\n";
回答by Sellorio
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.
对迟到的答案感到抱歉,但我遇到了类似的问题,直到我意识到 Visual Studio 2010char*
可视化器会忽略\r
和\n
字符。他们完全被忽略了。
Note: By visualiser I mean what you see when you hover over a char*
(or string
).
注意:我所说的可视化器是指当您将鼠标悬停在char*
( 或string
) 上时所看到的内容。
回答by Alexander Rafferty
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.
这将在每个字符或字符串后附加一个换行符,具体取决于 DataBegin 的实际类型。您的问题不在于您给出的代码示例。如果您提供预期和实际结果以及变量使用的数据类型,这将更有用。
回答by winux
Try this:
尝试这个:
ifstream inFile;
inFile.open(filename);
std::string entireString = "";
std::string line;
while (getline(inFile,line))
{
entireString.append(line);
entireString.append("\n");
}