473,287 Members | 1,655 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

convert string into an array

Hi,
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.
Thanks,
Sudzzz

Jul 3 '07 #1
11 5022
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
Jul 3 '07 #2
On Jul 3, 3:41 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
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.
Thanks,
Sudzzz

http://sudeeppillai.blogspot.com

Jul 3 '07 #3
Sudzzz wrote:
On Jul 3, 3:41 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
>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.
Yes, you can simulate C++ input, and it will involve some character
comparison, atoi (or strtol, more like it), append to array, sort of
algorithm. How do you think the compiler does that?
I don't know where to start.
Start here:

#include <string>
#include <vector>
#include <cassert>

int main() {
std::string mystring("{201,23,240,56,23,45,34,23}");
std::vector<intvint;

// write code to extract numbers from the 'mystring'
// and place them into 'vint'

assert(vint.size() == 8);
assert(vint[0] == 201);
assert(vint[1] == 23);
assert(vint[2] == 240);
assert(vint[3] == 56);
assert(vint[4] == 23);
assert(vint[5] == 45);
assert(vint[6] == 34);
assert(vint[7] == 23);
}

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 3 '07 #4
On Jul 3, 2:54 pm, Sudzzz <sudeep.um...@gmail.comwrote:
On Jul 3, 3:41 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
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.
Thanks,
Sudzzz

http://sudeeppillai.blogspot.com
You will have to tokenize the string, extracting characters between an
open curly brace '{', a comma ',' and a close curly brace '}'.

std::string str_array = "{201,23,240,56,23,45,34,23}";
std::string::size_type pos = 0;

std::vector<intint_array;

while (pos != std::string::npos)
{
std::string::size_type pos2;

pos = str_array.find_first_not_of("{,}", pos);
if (pos == std::string::npos) break;
pos2 = str_array.find_first_of("{,}", pos);

std::string str_number = str_array.substr(pos, pos2-pos+1);
int number = atoi(str_number.c_str()); //Might use a stream here
instead
int_array.push_back(number);

pos2 = pos;
}
I'm sure this will have some off-by-one errors and other bugs, because
I am not familiar with the signature of all these functions from
memory, but the idea is the same.

Jul 3 '07 #5
"Sudzzz" <su**********@gmail.comwrote in message
news:11**********************@k29g2000hsd.googlegr oups.com...
On Jul 3, 3:41 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
>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<intData;
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 << " ";

}
Jul 3 '07 #6
Sudzzz <su**********@gmail.comwrote:
I'm trying to convert a string something like this
"{201,23,240,56,23,45,34,23}" into an array in C++
Was BobR's answer not satisfactory to you when you asked this a week
ago?

http://groups.google.com/group/comp....50f516682ccbc/

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Jul 3 '07 #7
On Jul 3, 9:54 pm, Sudzzz <sudeep.um...@gmail.comwrote:
On Jul 3, 3:41 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
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.
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.
Is the number of elements constant, i.e. always 8. If so, use
boost::regex to validate the syntax and break the string down
into 8 substrings with just the numbers. Then use
istringstream, initialized with each of the substrings, to
convert. (This is definitly not the fastest solution, but it
should be adequate for three times a second, and it is certainly
the easiest to write.)

Otherwise, you'll have to write a simple parser yourself. Again,
you'll use istringstream. A couple of hints:

char ch ;
stream >ch ;

gets the next non-blank character. (Attention: the character is
extracted from the stream, and is no longer available.) And

int i ;
stream >i ;

to read an int.

So a priori, something like the following should do the trick:

char ch ;
stream >ch ;
if ( ! stream || ch != '{' ) {
error...
}
do
{
int i ;
stream >i >ch ;
if ( stream ) {
result.push_back( i ) ;
}
} while ( stream && ch == ',' ) ;
if ( ! stream || ch != '}' ) {
error ...
}

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jul 4 '07 #8
On Jul 3, 10:46 pm, "Jim Langston" <tazmas...@rocketmail.comwrote:
I would use a stringstream.
Just curious, but why a stringstream, and not an istringstream?

[...]
std::string str_array = "{201,23,240,56,23,45,34,23}";
std::stringstream Buffer;
Buffer << str_array;
Why those two lines, instead of simply:

std::istringstream Buffer( str_array ) ;
char Trash;
Buffer >Trash; // Throw away (
Throw away, or verify, as a syntax check? (In my experience,
you can never verify input too much.)
int Value;
std::vector<intData;
while ( Buffer >Value )
while ( Buffer >Value && Trash != '}' )
{
And

if ( Trash != (Data.empty() ? '{' : ',') ) {
Buffer.setstate( std::ios::failbit ) ;
}

here.
Data.push_back( Value );
Buffer >Trash; // Throw away , or )
}
And a final error check:

if ( ! (Buffer >std::ws && Buffer.get() == EOF ) {
error ...
}
// Display vector data
for ( std::vector<int>::iterator it = Data.begin(); it != Data.end();
++it )
std::cout << *it << " ";
}
(But I like your basic algorithm better than the one I
suggested.)

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jul 4 '07 #9

James Kanze <ja*********@gmail.comwrote in message...

/* """

On Jul 3, 10:46 pm, "Jim Langston" <tazmas...@rocketmail.comwrote:
I would use a stringstream.
Just curious, but why a stringstream, and not an istringstream?

[...]
std::string str_array = "{201,23,240,56,23,45,34,23}";
std::stringstream Buffer;
Buffer << str_array;
Why those two lines, instead of simply:

std::istringstream Buffer( str_array ) ;

""" */

Aww, c'mon James, we can do better than that. :-}

My original code, revised.
{
std::string stin( "{201,23,240,56,23,45,34,23}" );

std::istringstream in( stin.substr( 1, stin.size()-2 ) ); // <---- :-}
// assumes the strings are always *that* format, "{....}".

// now use this, or Jim's code from here ( with 'Trash' removed! [1]).
std::vector<intarray;
for( std::string line; std::getline( in, line, ',' ); ){
std::istringstream conv( line );
int num(0);
conv >num;
if( not conv ){ break;}
array.push_back( num );
// conv.clear(); conv.str("");
}
for( std::size_t i(0); i < array.size(); ++i ){
std::cout<< array.at( i ) <<" ";
}
}
// output:201 23 240 56 23 45 34 23

[1]
// Buffer >Trash; // Throw away (
char tst = Buffer.peek();
if( tst == '{' || tst == ',' || tst == '}' ){ Buffer.ignore(1); }

--
Bob R
POVrookie
Jul 5 '07 #10
"James Kanze" <ja*********@gmail.comwrote in message
news:11**********************@n60g2000hse.googlegr oups.com...
On Jul 3, 10:46 pm, "Jim Langston" <tazmas...@rocketmail.comwrote:
I would use a stringstream.

Just curious, but why a stringstream, and not an istringstream?
I don't know. I use stringstream for all types of conversion and it works.
What real advantage would istringstream give me?
[...]
std::string str_array = "{201,23,240,56,23,45,34,23}";
std::stringstream Buffer;
Buffer << str_array;

Why those two lines, instead of simply:

std::istringstream Buffer( str_array ) ;
Becuase I normally use stringstring in one of my templates:

template<typename T, typename F T StrmConvert( const F from )
{
std::stringstream temp;
temp << from;
T to = T();
temp >to;
return to;
}

If I change this to

std::string temp( from );

then I get compiler warnings at times depending on F.

warning C4244: 'argument' : conversion from 'const float' to
'std::_Iosb<_Dummy>::openmode', possible loss of data

and I go for 0% warnings in my code. I know that the form I use doesn't
give any warnings.
char Trash;
Buffer >Trash; // Throw away (

Throw away, or verify, as a syntax check? (In my experience,
you can never verify input too much.)
Agreed, but in most instances where I'm using stringstream for conversion
I've verified the data before I try to convert it, or the output makes it
obvious there was a problem. With user input data I would definately do
syntax checking of the string before/during/after the conversion.
int Value;
std::vector<intData;
while ( Buffer >Value )

while ( Buffer >Value && Trash != '}' )
This is really not needed though, unless there is extraneous data after
the ) such as

{201,23,240,56,23,45,34,23}75

etc... (not going to comment on the rest)
{

And

if ( Trash != (Data.empty() ? '{' : ',') ) {
Buffer.setstate( std::ios::failbit ) ;
}

here.
Data.push_back( Value );
Buffer >Trash; // Throw away , or )
}

And a final error check:

if ( ! (Buffer >std::ws && Buffer.get() == EOF ) {
error ...
}
// Display vector data
for ( std::vector<int>::iterator it = Data.begin(); it !=
Data.end();
++it )
std::cout << *it << " ";
}
(But I like your basic algorithm better than the one I
suggested.)

Jul 5 '07 #11
On Jul 5, 4:36 am, "Jim Langston" <tazmas...@rocketmail.comwrote:
"James Kanze" <james.ka...@gmail.comwrote in message
news:11**********************@n60g2000hse.googlegr oups.com...
On Jul 3, 10:46 pm, "Jim Langston" <tazmas...@rocketmail.comwrote:
I would use a stringstream.
Just curious, but why a stringstream, and not an istringstream?
I don't know. I use stringstream for all types of conversion
and it works. What real advantage would istringstream give
me?
It seems clearer to me if you're only going to be reading. I
use istringstream for input conversions (from text to whatever),
and ostringstream for output conversions (to text from
whatever). Somehow, it just seems clearer to say up front what
I'm going to do.
[...]
std::string str_array = "{201,23,240,56,23,45,34,23}";
std::stringstream Buffer;
Buffer << str_array;
Why those two lines, instead of simply:
std::istringstream Buffer( str_array ) ;
Becuase I normally use stringstring in one of my templates:
template<typename T, typename F T StrmConvert( const F from )
{
std::stringstream temp;
temp << from;
T to = T();
temp >to;
return to;
}
Sort of boost::lexical_cast, in sum. That's a different
context. (I'm not totally convinced that boost::lexical_cast is
a good idea. I'm not too hot on the idea that you can convert
anything to anything else, and never get a compiler error.)
If I change this to
std::string temp( from );
then I get compiler warnings at times depending on F.
warning C4244: 'argument' : conversion from 'const float' to
'std::_Iosb<_Dummy>::openmode', possible loss of data
and I go for 0% warnings in my code. I know that the form I
use doesn't give any warnings.
One could argue that since you're doing two conversions, you
should have two conversion objects, i.g.:

std::istringstream in ;
in << from ;
std::ostringstream out( in.str() ) ;
T to ;
out >to ;
return to ;

I'm not sure. As I said, I'm not too hot on this idea to begin
with. (If I were doing it, I'd certainly add a lot of error
handling. But I presume you've just stripped it out to make it
shorter for posting.)
char Trash;
Buffer >Trash; // Throw away (
Throw away, or verify, as a syntax check? (In my experience,
you can never verify input too much.)
Agreed, but in most instances where I'm using stringstream for
conversion I've verified the data before I try to convert it,
or the output makes it obvious there was a problem.
In most cases, I have too. Nothing like boost::regex
beforehand, to know what I'm dealing with. (But I thought I'd
mentionned that.) If you don't know the length in advance,
however, it's probably easier to do the checking dynamically.

I don't know the full context either. It might be worth
considering creating a decorator type for which you define an
operator>>, and use that, something like:

source >ArrayReader( array ) ;
With user input data I would definately do syntax checking of
the string before/during/after the conversion.
int Value;
std::vector<intData;
while ( Buffer >Value )
while ( Buffer >Value && Trash != '}' )
This is really not needed though, unless there is extraneous data after
the ) such as
{201,23,240,56,23,45,34,23}75
etc...
Yes. The real question is whether the string has been format
checked before hand, or not. If it has, then no further
checking should be necessary. If it hasn't, you probably want
to verify everything.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jul 5 '07 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: David Lawson | last post by:
I know how to conver a string to an array of strings, but I need to convert an ascii string to an array of integers (really unsigned chars). Eg, $str ="ABC"; needs to convert to something...
27
by: Trep | last post by:
Hi there! I've been having a lot of difficult trying to figure out a way to convert a terminated char array to a system::string for use in Visual C++ .NET 2003. This is necessary because I...
6
by: Ricardo Quintanilla | last post by:
i have a code that sends data to a socket listening over as400 platform, the socket responds to me as a "byte array". then i need to convert the "byte array" into a string. the problem is that...
6
by: Allan Ebdrup | last post by:
How do I easily convert a int to a string? Kind Regards, Allan Ebdrup
6
by: moondaddy | last post by:
I'm writing an app in vb.net 1.1 and need to convert a byte array into a string, and then from a string back to a byte array. for example Private mByte() as New Byte(4){11,22,33,44} Now how...
12
by: Peter | last post by:
Trying to convert string to byte array. the following code returns byte array of {107, 62, 194, 139, 64} how can I convert this string to a byte array of {107, 62, 139, 65} ...
19
by: est | last post by:
From python manual str( ) Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that...
9
by: myotheraccount | last post by:
Hello, Is there a way to convert a DataRow to a StringArray, without looping through all of the items of the DataRow? Basically, I'm trying to get the results of a query and put them into a...
5
by: da1978 | last post by:
Hi experts, I need to convert a string or a Byte array to a string byte array. Its relatively easy to convert a string to an char array or a byte array but not a STRING byte array. i.e. ...
0
Debadatta Mishra
by: Debadatta Mishra | last post by:
Introduction In this article I will provide you an approach to manipulate an image file. This article gives you an insight into some tricks in java so that you can conceal sensitive information...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.