从字符串c ++中读取所有整数 [英] Read all integers from string c++
问题描述
我需要一些帮助来获取std :: string中的所有整数并将每个整数转换为int变量。
I need some help with getting all the integers from a std::string and getting each of those integer into an int variable.
字符串示例:
<blah> hi 153 67 216
我希望程序忽略blah和hi并存储每个整数变成一个int变量。所以它就像是:
I would like the program to ignore the "blah" and "hi" and store each of the integers into an int variable. So it comes out to be like:
a = 153
b = 67
c = 216
然后我可以单独自由打印,如:
Then i can freely print each separately like:
printf("First int: %d", a);
printf("Second int: %d", b);
printf("Third int: %d", c);
谢谢!
推荐答案
您可以使用 scan_is
创建自己的函数来操作 std :: ctype
facet方法。然后,您可以将生成的字符串返回到 stringstream
对象,并将内容插入到整数中:
You can create your own function that manipulates a std::ctype
facet by using its scan_is
method. Then you can return the generated string to a stringstream
object and insert the contents to your integers:
#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;
}
输出:
Output:
1
2
3
1 2 3
这篇关于从字符串c ++中读取所有整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!