C++将多行字符转换为数组
作者:野牛程序员:2023-07-09 09:28:19 C++阅读 2860
在C++中,你可以使用字符串字面值和std::istringstream来将多行字符转换为数组。以下是一个示例代码:
#include <iostream>
#include <sstream>
#include <vector>
int main() {
const char* multilineString = R"(Line 1
Line 2
Line 3
Line 4)";
std::istringstream iss(multilineString);
std::vector<std::string> lines;
std::string line;
while (std::getline(iss, line)) {
lines.push_back(line);
}
// 打印每行字符串
for (const auto& str : lines) {
std::cout << str << std::endl;
}
return 0;
}在上面的代码中,我们定义了一个多行字符串multilineString,它使用了原始字符串字面值(Raw String Literal)的语法,其中以R"(开始,以)";结束。这样可以在字符串中包含换行符和其他特殊字符,而无需转义它们。
然后,我们将该多行字符串传递给std::istringstream,这是一个基于字符串的输入流。我们使用std::getline函数从流中逐行读取内容,并将每行字符串存储在std::vector<std::string>容器中。
最后,我们使用一个循环打印每行字符串。
运行上述代码将输出:
Line 1 Line 2 Line 3 Line 4
你可以根据需要修改和扩展这个示例,以满足你的具体需求。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:sfml库检测键盘事件
- 下一篇:c++中的&&是什么意思
