gpt4 book ai didi

c++ - 从字符串中读取整数

转载 作者:行者123 更新时间:2023-11-30 01:51:33 25 4
gpt4 key购买 nike

我有一个 "blah-blah..obj_xx..blah-blah" 形式的字符串,其中 xx 是数字。例如。该字符串可能是 "root75/obj_43.dat"

我想将 "xx"(或上面示例中的 43)读取为整数。我该怎么做?

我试图先找到“obj_”:

std::string::size_type const cpos = name.find("obj_");
assert(std::string::npos != cpos);

但下一步是什么?

最佳答案

我的 GCC 不完全支持正则表达式,但我认为这应该可行:

#include <iostream>
#include <string>
#include <regex>
#include <iterator>

int main ()
{
std::string input ("blah-blah..obj_42..blah-blah");
std::regex expr ("obj_([0-9]+)");

std::sregex_iterator i = std::sregex_iterator(input.begin(), input.end(), expr);
std::smatch match = *i;
int number = std::stoi(match.str());
std::cout << number << '\n';
}

关于c++ - 从字符串中读取整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26016590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com