首页 > 解决方案 > 如何通过行尾将字符串拆分为向量

问题描述

您好,所以我正在尝试将传入的请求逐行拆分为向量。

(示例请求)

GET / HTTP/1.1
Host: 192.168.0.51
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8

我想将每一行添加到向量中,我该如何实现?我一直在谷歌搜索,但似乎找不到答案。任何帮助表示赞赏。

标签: c++stringvector

解决方案


简单的解决方案是使用istringstreamand getline

#include <string>
#include <vector>
#include <sstream>

std::string request = ...;

std::istringstream buffer(request);
std::vector<std::string> lines;
std::string line;
while (getline(buffer, line))
{
    lines.push_back(line);
}

推荐阅读