Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - extract numbers from a string [closed]

Tags:

c++

string

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:

   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?

like image 346
user2064000 Avatar asked Jun 11 '13 11:06

user2064000


People also ask

How extract all numbers from string in C++?

Extract all integers from string in C++ The idea is to use stringstream:, objects of this class use a string buffer that contains a sequence of characters. Algorithm: Enter the whole string into stringstream. Extract the all words from string using loop.


1 Answers

A job for stringstreams, see it live: 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
like image 51
sehe Avatar answered Sep 21 '22 21:09

sehe