Re: convert string into an array
"Sudzzz" <sudeep.umich@gmail.com> wrote in message
news:1183492488.380094.177160@k29g2000hsd.googlegroups.com...
On Jul 3, 3:41 pm, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
Sudzzz wrote:
I'm trying to convert a string something like this
"{201,23,240,56,23,45,34,23}" into an array in C++
Please help.
We're happy to help. What have you done so far and what
are the problems? Read the FAQ, especially section 5.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Currently I have a string "{201,23,240,56,23,45,34,23}" which changes
frequently (possibly at 3Hz). The numbers can be any number having
less than 4 digits. I want to take this string and place it in an
array so that I can use for certain computational purposes. I've
looked through different possibilities one of which would involve an
extensive string comparison, atoi(), append to array sort of
algorithm. However I realized that when we input arrays c++ accepts it
in the same form as above and then I thought whether I could simulate c
++ input this string when asked for an array.
I don't know where to start.
I would use a stringstream. Output of following program is:
201 23 240 56 23 45 34 23
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
std::string str_array = "{201,23,240,56,23,45,34,23}";
std::stringstream Buffer;
Buffer << str_array;
char Trash;
Buffer >> Trash; // Throw away (
int Value;
std::vector<int> Data;
while ( Buffer >> Value )
{
Data.push_back( Value );
Buffer >> Trash; // Throw away , or )
}
// Display vector data
for ( std::vector<int>::iterator it = Data.begin(); it != Data.end();
++it )
std::cout << *it << " ";
}