C ++ - 从字符串中提取数字

时间:2013-06-11 11:13:03

标签: c++ string

假设我们在C ++中有一个C样式字符串,格式为[4 letters] [number] [number] ...。例如,字符串可能如下所示:

   abcd 1234    -6242          1212

应该注意的是,字符串应该有太多的空白(如上所示)。

如何提取这三个数字并将它们存储在数组中?

1 个答案:

答案 0 :(得分:14)

stringstreams的工作,现场直播: http://ideone.com/e8GjMg

#include <sstream>
#include <iostream>

int main()
{
    std::istringstream iss(" abcd 1234    -6242          1212");

    std::string s;
    int a, b, c;

    iss >> s >> a >> b >> c;

    std::cout << s << " " << a << " " << b << " " << c << std::endl;
}

打印

abcd 1234 -6242 1212