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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17042710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:52:40  来源:igfitidea点击:

C++ - extract numbers from a string

c++string

提问by user2064000

Let's say we have a C style string in C++ in the format [4 letters] [number] [number] .... For example, the string may look like:

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

   abcd 1234    -6242          1212

It should be noted that the string is expected to have too much whitespace (as seen above).

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

How would I extract these three numbers and store them in an array?

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

回答by sehe

A job for stringstreams, see it live: http://ideone.com/e8GjMg

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;
}

Prints

印刷

abcd 1234 -6242 1212