# Thread: Extracting numbers from a string

1. ## Extracting numbers from a string

Greetings. My problem here is not that urgent, but still, it's one that for some reason, still gives me headaches. It's like this:

I am entering some numbers from the keyboard, like this: 1 13 2 3 4 5. And I want to store them in a dynamically allocated vector. As you see here, there are 6 numbers. Parsing the string, I have to inform the compiler I have 6 numbers, so that will alocate memory for a vector holding exactly 6 numbers, like:
Code:
numbers = new int[6];
.

After that, I want to store those numbers in it. No matter how many spaces there are in the string, I just want those numbers stored in an array. If this is complicated or takes too much time to explain, then pass over it, but I would appreciate any help.

2. So basically you want to create a vector with n elements? You can do that like this:
Code:
std::vector someName(n);
or
Code:
std::vector someName;
someName.resize(n);
Then you can simply index them similar to an array.

Is that what you meant?

3. From the context, it seems he wants the source to "parse" these integers.

Veneficvs , what do you have?

Soma

4. Actually no. Let's say my string is: "15 2 38 4 666". Now, my vector will look like this:
numbers[0] = 15
numbers[1] = 2
numbers[2] = 38
numbers[3] = 4
numbers[4] = 666
I want the numbers sent into the array. It's like I would cin >> x, but this time it reads the values from the string.

5. Originally Posted by Veneficvs
Actually no. Let's say my string is: "15 2 38 4 666". Now, my vector will look like this:
numbers[0] = 15
numbers[1] = 2
numbers[2] = 38
numbers[3] = 4
numbers[4] = 666
I want the numbers sent into the array. It's like I would cin >> x, but this time it reads the values from the string.
Ah, so you want an istringstream. It works similar to cin (i.e. it's a stream as well), but reads from a string rather than stdin. It works like this:
Code:
#include <sstream>

...

std::istringstream someName(stringVariable);
Now you can treat someName similar to cin.

6. Thank you very much. I am sure I will do this now. I appreciate a lot.

7. it would look something like this I think

Code:
string numbers = "1 2 3 4 5";
vector<int> vec;
istringstream iss(numbers);

int temp;
while(iss >> temp)
{
vec.push_back(temp);
}