拥有一个字符串如何从第一个`/r/n/r/n`到字符串末尾的两行获取其内容? 我尝试在C++中创建简单的文件上传服务。我将所有用户请求主体作为一个大字符串。用户可以上传任何类型的数据。我只需要从请求boby字符串中获取用户文件内容

拥有一个字符串如何从第一个`/r/n/r/n`到字符串末尾的两行获取其内容? 我尝试在C++中创建简单的文件上传服务。我将所有用户请求主体作为一个大字符串。用户可以上传任何类型的数据。我只需要从请求boby字符串中获取用户文件内容,c++,string,C++,String,例如,现在我有了下一个与我的服务API提供商合作的代码: std::cout << "Request body: " << request->body << std::endl << "Request size: " << request->body.length() << std::endl; std::cout这不是最优雅的方法,但有一种选择是这样做: std::string contents = /*

例如,现在我有了下一个与我的服务API提供商合作的代码:

std::cout << "Request body: " << request->body << std::endl << "Request size: " <<  request->body.length() << std::endl;

std::cout这不是最优雅的方法,但有一种选择是这样做:

std::string contents = /* ... get the string ... */

/* Locate the start point. */
unsigned startPoint = contents.find("\r\n\r\n");
if (startPoint == string::npos) throw runtime_error("Malformed string.");

/* Locate the end point by finding the last newline, then backing up
 * to the newline before that.
 */
unsigned endPoint = contents.rfind('\n');
if (endPoint == string::npos || endPoint == 0) throw runtime_error("Malformed string.");
endPoint = contents.rfind('\n', endPoint - 1);
if (endPoint == string::npos) throw runtime_error("Malformed string.");

/* Hand back that slice of the string. */
return std::string(contents.begin() + startPoint, contents.begin() + endPoint);

您可以使用正则表达式来实现这一点。这个页面有一些不错的C++例子:

我建议编写代码来做。看起来像剪刀和浆糊是一条漫长的路。@Tom:那些破折号看起来像种子,也许可以用一个低成本的鸽子群来完成这项任务:这回答了问题,但正确的方法是从“请求主体:”行中获取终止符。第一个
if(endPoint==string::npos | endPoint==0)
是不必要的,因为字符串肯定包含
\r\n
。第二个
if
也:)字符串可能只包含
\r\n\r\n
。结果将包含一个额外的
\r
@Ben Voigt-我完全同意。
std::string contents = /* ... get the string ... */

/* Locate the start point. */
unsigned startPoint = contents.find("\r\n\r\n");
if (startPoint == string::npos) throw runtime_error("Malformed string.");

/* Locate the end point by finding the last newline, then backing up
 * to the newline before that.
 */
unsigned endPoint = contents.rfind('\n');
if (endPoint == string::npos || endPoint == 0) throw runtime_error("Malformed string.");
endPoint = contents.rfind('\n', endPoint - 1);
if (endPoint == string::npos) throw runtime_error("Malformed string.");

/* Hand back that slice of the string. */
return std::string(contents.begin() + startPoint, contents.begin() + endPoint);