string to array of numbers

hi.
i'm sure this has been asked before, but i haven't been able to find this, so i'll just ask.

i'd like to be able to read a line in input with cin, a line that must contain a series of integers separated by spaces, and that is ended by the pressing of the Enter key.
then extract all the integers from the string and put them in an array.

i'm not including any sort of error handling, so it should be simpler.

there probably are some methods of input manipulation that will do the trick but i don't know.

can anyone help?
If you can use vector<int> ,
1
2
3
4
5
6
7
8
std::istringstream in(your_string);
int x;
std::vector<int> your_array;
while(in>>x)
{
     your_array.push_back(x);
     in.clear();
}

I've not tested it, so do not use it directly; experiment a little first.
Last edited on
I don't know if this will help you more than what you have already got, but
Press enter twice to finish:
http://www.cplusplus.com/forum/beginner/2409/#msg9254
If you just use getline to read the line into a string, I don't see why you would need to press enter twice. That doesn't make sense to me. I'm also not sure what the in.clear() is for. Other than that, the example given looks fine to me. I just tried it and it worked but I didn't use that one line of code that I mentioned. If the while(...) test fails the loop will simply end without executing what is in the body again.
Last edited on
in.clear();
^ would be necessary if the object 'in' is used later in the code.....for..say..handling errors..when the while condition fails.
It depends on how many lines the user may input before terminating. I was only offering an option beyond what he had. (Had you followed my link you would have known that.)
Topic archived. No new replies allowed.