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

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

字符串示例:

 hi 153 67 216 

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

 a = 153 b = 67 c = 216 

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

 printf("First int: %d", a); printf("Second int: %d", b); printf("Third int: %d", c); 

谢谢!

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

 #include  #include  #include  #include  #include  #include  #include  std::string extract_ints(std::ctype_base::mask category, std::string str, std::ctype 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::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; } 

输出:

1 2 3

演示

  • 使用std::isdigit()检查字符是否为数字。 在未到达空间之前,逐步添加到单独的string
  • 然后使用std::stoi()将您的字符串转换为int。
  • 使用clear()方法clear()字符串的内容。
  • 转到第一步

重复直到未到达基本字符串的末尾。

首先使用字符串标记器

 std::string text = "token, test 153 67 216"; char_separator sep(", "); tokenizer< char_separator > tokens(text, sep); 

然后,如果您不确切知道将获得多少值,则不应使用单个变量abc ,而应使用int input[200]或更好的数组,如std::vector ,它可以适应数量你读过的元素。

 std::vector values; BOOST_FOREACH (const string& t, tokens) { int value; if (stringstream(t) >> value) //return false if conversion does not succeed values.push_back(value); } for (int i = 0; i < values.size(); i++) std::cout << values[i] << " "; std::cout << std::endl; 

你必须:

 #include  #include  #include  #include  //std::cout #include  #include  using boost::tokenizer; using boost::separator; 

顺便说一下,如果你正在编程C ++,你可能想避免使用printf ,而更喜欢std::cout

 #include  #include  #include  #include  #include  #include  int main() { using namespace std; int n=8,num[8]; string sentence = "10 20 30 40 5 6 7 8"; istringstream iss(sentence); vector tokens; copy(istream_iterator(iss), istream_iterator(), back_inserter(tokens)); for(int i=0;i 

要读取一行字符串并从中提取整数,

  getline(cin,str); stringstream stream(str); while(1) { stream>>int_var_arr[i]; if(!stream) break; i++; } } 

整数存储在int_var_arr []中