[英]C++ Retrieving Several Lines From a String
One of my assignments involves reading several strings into my program.我的一项任务是将几个字符串读入我的程序。 I've figured out how to store the strings into one, but now I need to retrieve each string by line.我已经想出了如何将字符串存储为一个,但现在我需要逐行检索每个字符串。 Any suggestions?有什么建议? Example:例子:
string s = "Hello
Welcome
Oranges
Bananas
Hi
Triangle"
I'm not allowed to store them into an array either;我也不允许将它们存储到数组中; they must all be contained in one string.它们必须全部包含在一个字符串中。
I would probably put the string into stringstream, then use something like std::getline
to read a line at a time from the string stream.我可能会将字符串放入 stringstream,然后使用std::getline
类的东西从字符串流中一次读取一行。 If you're really worried about execution speed, there are faster ways, but that would be the obvious first choice until profiling told you it wasn't allowable.如果您真的担心执行速度,还有更快的方法,但这将是显而易见的首选,直到分析告诉您这是不允许的。
For what it's worth, to embed a new-line into the string, you can use either \\n
, or switch to using a raw string literal:对于它的价值,要将换行符嵌入到字符串中,您可以使用\\n
,或切换到使用原始字符串文字:
string s = R"(Hello
Welcome
Oranges
Bananas
Hi
Triangle)";
With a raw string literal, embedded new-lines (and anything else) becomes part of the string itself.使用原始字符串文字,嵌入的换行符(和其他任何东西)成为字符串本身的一部分。 In a normal string literal, you have to use \\n
instead (if you want it to be portable, anyway).在普通的字符串文字中,您必须使用\\n
代替(如果您希望它是可移植的,无论如何)。
To render std::string
content as is use a raw string literal .要按原样呈现std::string
内容,请使用 原始字符串文字。 The following code would retrieve all single lines from a raw string literal:以下代码将从原始字符串文字中检索所有单行:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
int main() {
std::string s = R"x(Hello
Welcome
Oranges
Bananas
Hi
Triangle (and hey, some extra stuff in the line with parenthesis)
)x";
std::istringstream iss(s);
std::vector<std::string> lines;
std::string line;
while(getline(iss,line)) {
lines.push_back(line);
}
for(const auto& line : lines) {
std::cout << line << '\n';
}
}
See the working version online here .在此处在线查看工作版本。
With prior c++11 standards, you'll have to escape the line breaks with a \\
character like so:使用之前的 c++11 标准,您必须使用\\
字符转义换行符,如下所示:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
int main() {
std::string s = "Hello \n\
Welcome \n\
Oranges \n\
Bananas \n\
Hi \n\
Triangle (and hey, some extra stuff in the line with parenthesis)";
std::istringstream iss(s);
std::vector<std::string> lines;
std::string line;
while(getline(iss,line)) {
lines.push_back(line);
}
for(std::vector<std::string>::const_iterator it = lines.begin(); it != lines.end(); ++it) {
std::cout << *it << '\n';
}
}
See the other working online example .请参阅其他工作在线示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.