Pulling integers out of strings

How would I pull integers out of a string? I have the following string:

 
string my_string = "C(2)Fe(5)O(4)";


And I need to pull the numbers 2, 5, and 4 out of the string and store them in a different variable so I can multiply them by other numbers. Is there any way to do this?
Last edited on
using stringstream

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <sstream>

string my_string = "C(2)Fe(5)O(4)";

std::stringstream StrToNum;

StrToNum << my_string;

int num1, num2, num3;

StrToNum >> num1;
StrToNum >> num2;
StrToNum >> num3;
I was able to use getline to pull in just a small piece of data, so my string is now:

 
string my_string = "C(2";


But I still can't get the code that you posted to work.

My code:

1
2
3
4
5
6
7
8
9
10
11
12
void integer_extract()
{
    stringstream stream;
    int extract;
    my_string = "C(2";

    stream << my_string;

    stream >> extract;

    cout << "Value of extract " << extract << endl;
}


And I get 0 as output. I should get 2. What am I doing wrong?
1
2
3
4
5
6
7
8
9
10
11
12
#include <string>

int main()
{
	std::string my_string = "C(2)Fe(5)O(4)";

	for (unsigned int i=0; i<my_string.size(); ++i)
	{
		if(my_string[i] >= 48 && my_string[i] <=57)  //character is a number in that case
			my_string.erase(my_string.begin()+i);
	}
}
Topic archived. No new replies allowed.