从字符串c ++中读取所有整数

Mik*_*ike 4 c c++ string integer

我需要一些帮助,从std :: string中获取所有整数,并将每个整数转换为int变量.

字符串示例:

<blah> hi 153 67 216
Run Code Online (Sandbox Code Playgroud)

我希望程序忽略"blah"和"hi"并将每个整数存储到一个int变量中.所以它就像是:

a = 153
b = 67
c = 216
Run Code Online (Sandbox Code Playgroud)

然后我可以自由地分别打印每个像:

printf("First int: %d", a);
printf("Second int: %d", b);
printf("Third int: %d", c);
Run Code Online (Sandbox Code Playgroud)

谢谢!

0x4*_*2D2 8

您可以std::ctype使用其scan_is方法创建自己的操作构面的函数.然后,您可以将生成的字符串返回给stringstream对象,并将内容插入到整数中:

#include <iostream>
#include <locale>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <cstring>

std::string extract_ints(std::ctype_base::mask category, std::string str, std::ctype<char> const& facet)
{
    using std::strlen;

    char const *begin = &str.front(),
               *end   = &str.back();

    auto res = facet.scan_is(category, begin, end);

    begin = &res[0];
    end   = &res[strlen(res)];

    return std::string(begin, end);
}

std::string extract_ints(std::string str)
{
    return extract_ints(std::ctype_base::digit, str,
         std::use_facet<std::ctype<char>>(std::locale("")));
}

int main()
{
    int a, b, c;

    std::string str = "abc 1 2 3";
    std::stringstream ss(extract_ints(str));

    ss >> a >> b >> c;

    std::cout << a << '\n' << b << '\n' << c;
}
Run Code Online (Sandbox Code Playgroud)

输出:

1 2 3

演示