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.
// 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...
#include <iostream>
#include <cstdlib>
#include <string>
usingnamespace 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;