1. spliting strings

Hey,
I'm working on a program where i need to enter a string of numbers and then seperate the numbers by the at every space.
Example:
input "103 105 235" then i want something like an array with array[0] = 103, array[1] = 105, ect.
any help would be greatly appricated

2. do you want the numbers as strings or integers?

i.e. array[0] = 103 or array[0] = "103"

I'd look at the stringstream class

3. First get the amount of spaces, then make an array of that size + 1. Then loop through the inputed string, throwing chars into a temp buffer. Once you hit a space, convert the temp buffer into an int, and put it in the array, and so on and so forth. Btw, this sounds like homework.

4. Originally Posted by Yarin
First get the amount of spaces, then make an array of that size + 1. Then loop through the inputed string, throwing chars into a temp buffer. Once you hit a space, convert the temp buffer into an int, and put it in the array, and so on and so forth. Btw, this sounds like homework.
meh, too much like work. use a stringstream.

5. Code:
char line[] = "103 56 73 89";
int numbers[99];
int numbCount = 0;
char* word = strtok(line, " ");
while(word != NULL && numbCount < 99)
{
numbers[numbCount] = atoi(word);
word = strtok(NULL, " ");
numbCount++;
}

6. better to use stringstream over the strtok, that has some issues

7. Code:
std::string input("103 56 73 89");
std::istringstream s(input);
std::vector<int> nums;
int temp;
while(s >> temp) nums.push_back(temp);
or maybe if you prefer
Code:
int* nums;
std::string input = "103 56 73 89";
int elements = std::count(input.begin(),input.end(), ' ') + 1;
num = new int[elements];
std::istringstream s(input);
for(int x = 0; x < elements, ++x) s >> nums[x];

8. You don't need to use a stringstream if the input is already from a stream like standard input. For example:

Code:
vector<int> targetArray;
copy( istream_iterator<int>(cin), istream_iterator<int>(), back_inserter(targetArray) );

9. One could also eliminate the explicit loop in the former example by using std::copy(), e.g.,
Code:
std::string input("103 56 73 89");
std::istringstream s(input);
std::vector<int> nums;
std::copy(std::istream_iterator<int>(s), std::istream_iterator<int>(),
std::back_inserter(nums));