473,770 Members | 4,355 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Required string parser

Hello,

I am writing one application in which I am getting data as a string "
10 | 20 | 30 | 40 | 50" now my aim is to parse those string, split it
by pipe '|' and get integer outputs in some array or other data
structure.....

do anybody worked in the same functionality, then please let me know.

Thanks,
Rushik.

Oct 4 '06 #1
8 1898


? "rushik" <ru************ *@gmail.com???? ?? ??? ??????
news:11******** **************@ c28g2000cwb.goo glegroups.com.. .
Hello,

I am writing one application in which I am getting data as a string "
10 | 20 | 30 | 40 | 50" now my aim is to parse those string, split it
by pipe '|' and get integer outputs in some array or other data
structure.....

do anybody worked in the same functionality, then please let me know.

Thanks,
Rushik.
You can use the strtok function:
http://www.cplusplus.com/ref/cstring/strtok.html

Be careful though, strtok works with char *.
--
Serafeim
Oct 4 '06 #2

Papastefanos Serafeim wrote:
? "rushik" <ru************ *@gmail.com???? ?? ??? ??????
news:11******** **************@ c28g2000cwb.goo glegroups.com.. .
Hello,

I am writing one application in which I am getting data as a string "
10 | 20 | 30 | 40 | 50" now my aim is to parse those string, split it
by pipe '|' and get integer outputs in some array or other data
structure.....

do anybody worked in the same functionality, then please let me know.

Thanks,
Rushik.
Hi,

Seems simple. My suggestion...

Iterate till length of string
{
Iterate till '|' found
{
extract char at ctr and concatenate char to std::string
increment ctr
}
increment ctr
if(length of string 0)
{
convert temp string into number using atoi() and store in int vector
reset std::string
}
}

Convert the pseudo code into C++ :) If it is production code, then you
will obviously put in more checks.

Regards,
Abhishek Srivastava

Oct 4 '06 #3

rushik wrote:
Hello,

I am writing one application in which I am getting data as a string "
10 | 20 | 30 | 40 | 50" now my aim is to parse those string, split it
by pipe '|' and get integer outputs in some array or other data
structure.....

do anybody worked in the same functionality, then please let me know.

Thanks,
Rushik.
If however you prefer doing it yourself, the std::string is well
capable of pumping out a parser. Keep in mind that you should use
std::string::si ze_type to hold those values returned by find_first_of
-like member functions. You can then std::istringstr eam the substrings
to generate the numbers. The std::string class includes a panoply of
member functions and ctors that will let you substring at construction
time or using assign(...), etc.

Here is one nasty example that uses 2 functions, one to populate a
container of relevant substrings and another templated function to
convert the substrings into a container of numbers. It'll work with
any seperator including spaces, comma, colon, etc or any combination of
these. The error checking is rudimentary at best (you need to supply
the correct seperator).

Take note that t_track is used to prevent find_first_of from rolling up
to std::string::np os ( a costly operation on some implementations ).
Also, there is most likely better ways of doing this.
check out boost's tokenizer, for example.

#include <iostream>
#include <ostream>
#include <string>
#include <vector>
#include <sstream>
#include <stdexcept>

void parser( std::vector<std ::string>& r_v,
const std::string& s,
const std::string& r_sep )
{
std::string::si ze_type t_track = s.find_last_of( r_sep);
if ( t_track == std::string::np os )
{
throw std::exception( ); // no sep found
}
std::string s_temp(s); // decapitating string
while ( t_track != std::string::np os )
{
std::string::si ze_type t_size = s_temp.find_fir st_of(r_sep);
std::string s_add(s_temp, 0, t_size);
std::cout << "s_add = " << s_add << std::endl;
r_v.push_back(s _add);
t_track = t_track - s_add.size() - r_sep.size(); // npos?
s_temp.assign(s _temp, t_size + r_sep.size(), s_temp.size());
std::cout << "s_temp = " << s_temp << std::endl;
}
r_v.push_back(s _temp); // push last one
}

template< typename T >
void converter( std::vector<std ::string>& r_vs,
std::vector<T>& r_vt )
{
typedef std::vector<std ::string>::iter ator VIter;
VIter iter = r_vs.begin();
for (iter; iter != r_vs.end(); ++iter)
{
T t;
std::istringstr eam iss(*iter);
iss >t;
r_vt.push_back( t);
}
}

int main()
{
std::string s("10 | 20 | 30 | 40 | 50");
// std::string s("-11 20 -3 2 4 3 1 -6");
std::vector<std ::stringvs;

try
{
parser(vs, s, " | ");
std::vector<int vn;
converter<int>( vs, vn);
for (size_t i = 0; i < vn.size(); ++i)
{
std::cout << "vn[ " << i << "] = ";
std::cout << vn.at(i) << std::endl;
}
}
catch ( const std::exception& e )
{
std::cout << "Error !" << std::endl;
}

return 0;
}

/*
s_add = 10
s_temp = 20 | 30 | 40 | 50
s_add = 20
s_temp = 30 | 40 | 50
s_add = 30
s_temp = 40 | 50
s_add = 40
s_temp = 50
vn[ 0] = 10
vn[ 1] = 20
vn[ 2] = 30
vn[ 3] = 40
vn[ 4] = 50
*/

Oct 4 '06 #4
On 4 Oct 2006 09:49:27 -0700, "Salt_Peter " <pj*****@yahoo. comwrote:
>
template< typename T >
void converter( std::vector<std ::string>& r_vs,
std::vector<T>& r_vt )
{
typedef std::vector<std ::string>::iter ator VIter;
VIter iter = r_vs.begin();
for (iter; iter != r_vs.end(); ++iter)
{
T t;
std::istringstr eam iss(*iter);
iss >t;
r_vt.push_back( t);
}
}

int main()
{
std::string s("10 | 20 | 30 | 40 | 50");
// std::string s("-11 20 -3 2 4 3 1 -6");
std::vector<std ::stringvs;

try
{
parser(vs, s, " | ");
std::vector<int vn;
converter<int>( vs, vn);
for (size_t i = 0; i < vn.size(); ++i)
{
std::cout << "vn[ " << i << "] = ";
std::cout << vn.at(i) << std::endl;
}
}
catch ( const std::exception& e )
{
std::cout << "Error !" std::endl;
}

return 0;
}
Your try/catch blocks seem to indicate sufficient error treatment. But
the most problematic part of the program, the conversion between sting
and int (with inefficient stringstream), omits any error handling.

Best wishes,
Roland Pibinger
Oct 4 '06 #5

rushik wrote:
Hello,

I am writing one application in which I am getting data as a string "
10 | 20 | 30 | 40 | 50" now my aim is to parse those string, split it
by pipe '|' and get integer outputs in some array or other data
structure.....

do anybody worked in the same functionality, then please let me know.

Thanks,
Rushik.
std::string data="10 | 20 | 30 | 40 | 50";
std::stringstre am sstr(data); // include sstream
int i1, i2, i3,i4,i5;
char c;
sstr >i1>>c>>i2>>c>> i3>>c>>i4>>c>>i 5;

or like this
int i;
char c;
std::vector<int vec;
while(sstr.rdbu f()->in_avail())
{
sstr>>i>>c;
vec.push_back(i ) ;
}

There are many possibilities.
strtok and sscanf are the worst of them.

Best Regards,
Valentin Heinitz

http://heinitz-it.de

Oct 4 '06 #6

Roland Pibinger wrote:
On 4 Oct 2006 09:49:27 -0700, "Salt_Peter " <pj*****@yahoo. comwrote:

template< typename T >
void converter( std::vector<std ::string>& r_vs,
std::vector<T>& r_vt )
{
typedef std::vector<std ::string>::iter ator VIter;
VIter iter = r_vs.begin();
for (iter; iter != r_vs.end(); ++iter)
{
T t;
std::istringstr eam iss(*iter);
iss >t;
r_vt.push_back( t);
}
}

int main()
{
std::string s("10 | 20 | 30 | 40 | 50");
// std::string s("-11 20 -3 2 4 3 1 -6");
std::vector<std ::stringvs;

try
{
parser(vs, s, " | ");
std::vector<int vn;
converter<int>( vs, vn);
for (size_t i = 0; i < vn.size(); ++i)
{
std::cout << "vn[ " << i << "] = ";
std::cout << vn.at(i) << std::endl;
}
}
catch ( const std::exception& e )
{
std::cout << "Error !" std::endl;
}

return 0;
}

Your try/catch blocks seem to indicate sufficient error treatment. But
the most problematic part of the program, the conversion between sting
and int (with inefficient stringstream), omits any error handling.

Best wishes,
Roland Pibinger
I agree. i see that a simple if_conversion_t est should provide a simple
solution:
http://www.parashift.com/c++-faq-lit...al-issues.html
[39.2] How do I convert a std::string to a number?

int n;
std::string s;
std::istringstr eam iss(s);
if ( !(i >n) ) // test
throw std::exception( );
....

Have you a better proposal insofar as the std::stringstre am is
concerned?
Did you mean inefficient as in the stream being regenerated over each
loop?
Or rdbuf() and clear() is what you had in mind?

Oct 5 '06 #7

Roland Pibinger wrote:
On 4 Oct 2006 09:49:27 -0700, "Salt_Peter " <pj*****@yahoo. comwrote:

template< typename T >
void converter( std::vector<std ::string>& r_vs,
std::vector<T>& r_vt )
{
typedef std::vector<std ::string>::iter ator VIter;
VIter iter = r_vs.begin();
for (iter; iter != r_vs.end(); ++iter)
{
T t;
std::istringstr eam iss(*iter);
iss >t;
r_vt.push_back( t);
}
}

int main()
{
std::string s("10 | 20 | 30 | 40 | 50");
// std::string s("-11 20 -3 2 4 3 1 -6");
std::vector<std ::stringvs;

try
{
parser(vs, s, " | ");
std::vector<int vn;
converter<int>( vs, vn);
for (size_t i = 0; i < vn.size(); ++i)
{
std::cout << "vn[ " << i << "] = ";
std::cout << vn.at(i) << std::endl;
}
}
catch ( const std::exception& e )
{
std::cout << "Error !" std::endl;
}

return 0;
}

Your try/catch blocks seem to indicate sufficient error treatment. But
the most problematic part of the program, the conversion between sting
and int (with inefficient stringstream), omits any error handling.

Best wishes,
Roland Pibinger
I agree. i see that a simple if_conversion_t est should provide a simple
solution:
http://www.parashift.com/c++-faq-lit...al-issues.html
[39.2] How do I convert a std::string to a number?

int n;
std::string s;
std::istringstr eam iss(s);
if ( !(iss >n) ) // test
throw std::exception( );
....

Have you a better proposal insofar as the std::stringstre am is
concerned?
Did you mean inefficient as in the stream being regenerated over each
loop?
Or rdbuf() and clear() is what you had in mind?

Oct 5 '06 #8
On 4 Oct 2006 19:49:56 -0700, "Salt_Peter " <...@yahoo.comw rote:
>i see that a simple if_conversion_t est should provide a simple
solution:
http://www.parashift.com/c++-faq-lit...al-issues.html
[39.2] How do I convert a std::string to a number?

int n;
std::string s;
std::istringst ream iss(s);
if ( !(i >n) ) // test
throw std::exception( );
...

Have you a better proposal insofar as the std::stringstre am is
concerned?
Did you mean inefficient as in the stream being regenerated over each
loop?
At least move the stringstream out of the loop. Alternatively you may
consider to encapsulate strtol or similar functions (but those
functions are a little tricky).

Best wishes,
Roland Pibinger

Oct 5 '06 #9

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

Similar topics

0
1784
by: Matthieu Gaillet | last post by:
Hello everyone, I try to launch a simple aspx (webmatrix) page onto an W2k / IIS5.0 / .net framework 1.1 but still get this error page : Server Error in '/pagaille' Application. ---------------------------------------------------------------------------- ---- Configuration Error
6
6787
by: yzzzzz | last post by:
Hi, In which cases is the <?xml version="1.0" encoding="UTF-8"?> processing instruction required at the beginning of an XML document, for the document to be valid? e.g. does it depend on the encoding used in the document, of the version of XML being used... Thanks.
4
1882
by: Sridhar | last post by:
HI All, Currently writing a small program and here is my xml file and program. --------------------------------------------------------------------------------- <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <abc> <featureKey id="F1/1"> <description>Lawful interception</description> <start>2000-01-01</start>
5
2557
by: Graham | last post by:
I have created a custom MembershipProvider called "LassieMembershipProvider" that derives from "MembershipProvider". This providor is located in a Businesslogic layer dll called "Enlighten.LinkMad.Businesslogic". In one of my frontend websites I use this type to authenticate a user who is trying to login. The following excerpt is from the web.config of the particular site showing the reference to the custom provider, allowing .Net to do...
4
5895
by: sturnfie | last post by:
Hey all, I recently came across the xml.sax libraries and am trying to use them. I am currently making a string variable, and am attempting to pass it into a parser instance as follows: def parseMessage(self, message): #create a XML parser parser = make_parser() #create an instance of our handler class #generic, prints out to screen on all events
1
7128
by: spardi | last post by:
I try to launch a simple aspx (webmatrix) page onto an W2k / IIS5.0 / .net framework 1.1 but still get this error page : Server Error in '/pagaille' Application. ---------------------------------------------------------------------------- ---- Configuration Error Description: An error occurred during the processing of a configuration file
11
303
by: xyz | last post by:
I have a string 16:23:18.659343 131.188.37.230.22 131.188.37.59.1398 tcp 168 for example lets say for the above string 16:23:18.659343 -- time 131.188.37.230 -- srcaddress 22 --srcport 131.188.37.59 --destaddress 1398 --destport tcp --protocol
9
6283
nine72
by: nine72 | last post by:
Ok, so I have figured out how to parse an custom returned XML doc (actually a string that I made into a doc for testing). At this point I am attempting to integrate my parse routine into my main code and I am having an issue getting it to mesh, and am looking for a little help in how to 1) combine the two and 2) how to catch the incoming xml string. FYI the string is sent to me as a return message to an xml message that I send first....
4
4544
by: stroudg2 | last post by:
Situation: I have been tasked to provide a non-intrusive solution to allow .NET web services to grab an incoming SOAP header and process the credentials stored within in such a way that a credential object is returned to the web method so they can access the appropriate role information to add to database query. In order to accomplish this, I created two class libraries, one that provides the "CredentialProfile" object definition, and one...
0
9602
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10237
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
10071
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10017
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7431
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
6690
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
5326
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5467
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3589
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.