473,799 Members | 3,810 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 5060
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...@com Acast.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...@com Acast.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<int vint;

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

assert(vint.siz e() == 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...@g mail.comwrote:
On Jul 3, 3:41 pm, "Victor Bazarov" <v.Abaza...@com Acast.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::si ze_type pos = 0;

std::vector<int int_array;

while (pos != std::string::np os)
{
std::string::si ze_type pos2;

pos = str_array.find_ first_not_of("{ ,}", pos);
if (pos == std::string::np os) break;
pos2 = str_array.find_ first_of("{,}", pos);

std::string str_number = str_array.subst r(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**********@g mail.comwrote in message
news:11******** **************@ k29g2000hsd.goo glegroups.com.. .
On Jul 3, 3:41 pm, "Victor Bazarov" <v.Abaza...@com Acast.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::stringstre am 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 << " ";

}
Jul 3 '07 #6
Sudzzz <su**********@g mail.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...@g mail.comwrote:
On Jul 3, 3:41 pm, "Victor Bazarov" <v.Abaza...@com Acast.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_bac k( i ) ;
}
} while ( stream && ch == ',' ) ;
if ( ! stream || ch != '}' ) {
error ...
}

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
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...@rock etmail.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::stringstre am Buffer;
Buffer << str_array;
Why those two lines, instead of simply:

std::istringstr eam 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<int Data;
while ( Buffer >Value )
while ( Buffer >Value && Trash != '}' )
{
And

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

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 objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jul 4 '07 #9

James Kanze <ja*********@gm ail.comwrote in message...

/* """

On Jul 3, 10:46 pm, "Jim Langston" <tazmas...@rock etmail.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::stringstre am Buffer;
Buffer << str_array;
Why those two lines, instead of simply:

std::istringstr eam 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::istringstr eam 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<int array;
for( std::string line; std::getline( in, line, ',' ); ){
std::istringstr eam 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

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

Similar topics

4
6114
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 like this: $buf = array(0x41, 0x42, 0x43); Anyone know how? I haven't been able to find a way.
27
51737
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 have some legcay C code that needs to process a string taken from a textbox, then I need to re-display the string as the textbox->Text. I easily found how to convert from system::string to char but I can't figure out how to go the other way!!
6
10236
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 the data converted from the byte array into a string , is not what i expect. example: - the data returned from the socket is (byte array) "Usuario Sin Atribuciones Para Esta Función"
6
12769
by: Allan Ebdrup | last post by:
How do I easily convert a int to a string? Kind Regards, Allan Ebdrup
6
53726
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 do I convert it to: dim myStr as string = "11,22,33,44"
12
13567
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} System.Text.UTF8Encoding str = new System.Text.UTF8Encoding(); string s = new string((char)107, 1); s += new string((char)62, 1);
19
5349
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 str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ''.
9
35855
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 listbox. Right now it is done like this:
5
4854
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. Dim Array() As Char Dim strwork As String = "76A3kj9d6" Array = strwork.ToCharArray OR
0
10785
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 inside an image, hide your complete image as text ,search for a particular image inside a directory, minimize the size of the image. However this is not a new concept, there is a concept called Steganography which enables to conceal your secret...
0
9543
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10488
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10029
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9077
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7567
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6808
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5588
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4144
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3761
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.