Extracting numbers

Hello, I'm new to C++, how can I make a subroutine that, when I pass the string "100-1909" it extracts the two parts of "100-1909", and, using pointers, it returns 100 & 1909.
I have no idea how to do this.
Thanks.
Last edited on
std::stringstream
How do I use that?
#include <sstream>

string a_string;
int a_number;
a_string = "2001";
stringstream a_stream(a_string);
a_stream >> a_number;

// now a_number is an integer 2001.. so if you can separate the string somehow, maybe using .substr() you can use this.. it gets more complicated if you want to draw multiple numbers from one string separated by the "-" or whatever that's another issue, you'll need to make some if(){} and while(){} loops...

EDIT! use:
#include <sstream>

not: #include <stringstream>
Lol my bad.
Last edited on
More than one way to do this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <cstdlib>
#include <string>

    using namespace std;

int main()
{
    string s("102-1890");
    
    char * endptr;

    long a = strtol(s.c_str(), &endptr, 10);    // get the first integer
    long b = strtol(endptr+1, &endptr, 10);     // get the second integer

    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    return 0;
}

Output:
a = 102
b = 1890

After line 13 has executed, endptr willl point to the character after the first number, that is, the '-' character. Hence endptr+1 on line 14, to skip that character.
http://www.cplusplus.com/reference/cstdlib/strtol/



Or using stringstream:
1
2
3
4
5
6
7
8
9
    string s("102-1890");

    char ch;
    int a, b;
    stringstream ss(s);
    ss >> a >> ch >>  b;

    cout << "a = " << a << endl;
    cout << "b = " << b << endl;


Last edited on
Thanks!
Topic archived. No new replies allowed.