473,811 Members | 3,298 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Parsing string

Hi, I need to parse a string used to represent a time and then
populate
a simple time struct. The time string will always be this format

23:45.45 ie hours separated from mins by ':' and minutes separated
from seconds by '.'
The string will be 8 chars in len. I've come up with some simple code
below
but am wondering do i really need a wstringstream and a string to do
this. Can
the parsing just be done with a wstringstream.

struct TIMESTRUCT
{
unsigned short Hour;
unsigned short Minute;
unsigned short Second;
}

bool TimeParser(cons t std::wstring& time, TIMESTRUCT& st)
{
std::wistringst ream tmp;
// a time string must be 8 chars in len
assert(time.siz e() == 8);

tmp.str(time.su bstr(0, 2));
tmp >st.Hour;
if (time[2] != ':') return false;
tmp.clear();
tmp.str(time.su bstr(3, 2));
tmp >st.Minute;
if (time[5] != '.') return false;
tmp.clear();
tmp.str(time.su bstr(6, 2));
tmp >st.Second;
return true;
}

int main()
{
TIMESTRUCT st;
std::wstring t(L"23:34.45") ;
TimeParser(t, st);
return 0;
}
Jun 27 '08 #1
5 1900
tech wrote:
Hi, I need to parse a string used to represent a time and then
populate a simple time struct. The time string will always be
this format 23:45.45 ie hours separated from mins by ':' and
minutes separated from seconds by '.'
The string will be 8 chars in len. I've come up with some simple code
below but am wondering do i really need a wstringstream and a
string to do this. Can
the parsing just be done with a wstringstream.
This would work with istringstream if you change
its formal argument from
bool TimeParser(cons t std::wstring& time, TIMESTRUCT& st)
to bool TimeParser(cons t std::string& time, TIMESTRUCT& st)

and the actual data from
int main()
{
TIMESTRUCT st;
std::wstring t(L"23:34.45") ;
to std::string t("23:34.45") ;
BTW, some people tend to do almost everythin
in regular expressions (which will be there
soon and are long available via boost).

Your TimeParser would be much simpler, like:

...
#include <boost/regex.hpp>
using namespace boost;
...

bool TimeParser(cons t std::string& time, TIMESTRUCT& st)
{
cmatch m;
if(regex_match( time.c_str(), m, regex("^(\\d{2} ):(\\d{2})\\.(\ \d{2})$"))) {
st.Hour = atoi(m[1].first);
st.Minute = atoi(m[2].first);
st.Second = atoi(m[3].first);
return true;
}
return false;
}

The required format "dd:dd.dd" would be checked by
the regular expression and all would be fine.

Regards

M.
Jun 27 '08 #2
On Jun 25, 2:30 pm, Mirco Wahab <wa...@chemie.u ni-halle.dewrote:
tech wrote:
BTW, some people tend to do almost everythin
in regular expressions (which will be there
soon and are long available via boost).
Your TimeParser would be much simpler, like:
...
#include <boost/regex.hpp>
using namespace boost;
...
bool TimeParser(cons t std::string& time, TIMESTRUCT& st)
{
cmatch m;
if(regex_match( time.c_str(), m, regex("^(\\d{2} ):(\\d{2})\\.(\ \d{2})$"))) {
st.Hour = atoi(m[1].first);
st.Minute = atoi(m[2].first);
st.Second = atoi(m[3].first);
return true;
}
return false;
}
The required format "dd:dd.dd" would be checked by
the regular expression and all would be fine.
Two small nits: first, regex_match can take iterators, so you
can just write:
if ( regex_match( time.begin(), time.end(), m, expr ) ) ...
And since the expression is a constant, that's how I'd write it:
static regex const expr( "^(\\d{2}):(\\d {2})\\.(\\d{2}) $" ) ;
(at the start of the function, before the if).

--
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
Jun 27 '08 #3
On Jun 25, 4:37*pm, James Kanze <james.ka...@gm ail.comwrote:
On Jun 25, 2:30 pm, Mirco Wahab <wa...@chemie.u ni-halle.dewrote:


tech wrote:
BTW, some people tend to do almost everythin
in regular expressions (which will be there
soon and are long available via boost).
Your TimeParser would be much simpler, like:
* *...
* *#include <boost/regex.hpp>
* *using namespace boost;
* *...
* *bool TimeParser(cons t std::string& time, TIMESTRUCT& st)
* {
* *cmatch m;
* *if(regex_match (time.c_str(), m, regex("^(\\d{2} ):(\\d{2})\\.(\ \d{2})$"))) {
* * * st.Hour * = atoi(m[1].first);
* * * st.Minute = atoi(m[2].first);
* * * st.Second = atoi(m[3].first);
* * * return true;
* *}
* *return false;
* }
The required format "dd:dd.dd" would be checked by
the regular expression and all would be fine.

Two small nits: first, regex_match can take iterators, so you
can just write:
* * if ( regex_match( time.begin(), time.end(), m, expr ) ) ...
And since the expression is a constant, that's how I'd write it:
* * static regex const expr( "^(\\d{2}):(\\d {2})\\.(\\d{2}) $" ) ;
(at the start of the function, before the if).

--
James Kanze (GABI Software) * * * * * * email:james.ka. ..@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- Hide quoted text -

- Show quoted text -
Thanks guys but i was wondering whether i could do my simple function
with just
a stringstream rather with a string aswell.
Jun 27 '08 #4
tech wrote:
Thanks guys but i was wondering whether i could do my simple function
with just a stringstream rather with a string aswell.
I don't completely understand what you
want and what you are trying to
accomplish. What means:
/with just a stringstream rather with a string aswell/

If you only want to get rid of the w_ functions, just
don't use them:

bool TimeParser(cons t std::string& time, TIMESTRUCT& st)
{
assert(time.siz e() == 8); // a time string must be 8 chars
char a ,b;
std::istringstr eam tmp(time);
tmp > st.Hour >a > st.Minute >b >st.Second;
return a == ':' && b == '.' ? true : false;
}

int main()
{
TIMESTRUCT st;
std::string t("03:34.45") ;
TimeParser(t, st);
return 0;
}

But maybe there's something else?

Regards

M.

Jun 27 '08 #5
James Kanze wrote:
On Jun 25, 2:30 pm, Mirco Wahab <wa...@chemie.u ni-halle.dewrote:
> bool TimeParser(cons t std::string& time, TIMESTRUCT& st)
{
cmatch m;
if(regex_match( time.c_str(), m, regex("^(\\d{2} ):(\\d{2})\\.(\ \d{2})$"))) {
st.Hour = atoi(m[1].first);
st.Minute = atoi(m[2].first);
st.Second = atoi(m[3].first);
return true;
}
return false;
}

Two small nits: first, regex_match can take iterators, so you
can just write:
if ( regex_match( time.begin(), time.end(), m, expr ) ) ...
This would require the smatch overloaded 'regex_match',
which returns std::string objects in matches and does,
in this case, also provide a version that uses the
plain std::string:

bool TimeParser(cons t std::string& time, TIMESTRUCT& st)
{
using namespace boost;
smatch m;
static regex r("^(\\d{2}):(\ \d{2})\\.(\\d{2 })$");
if(regex_match( time, m, r)) {
st.Hour = atoi(m[1].str().c_str()) ;
st.Minute = atoi(m[2].str().c_str()) ;
st.Second = atoi(m[3].str().c_str()) ;
return true;
}
return false;
}

The use of the smatch-overloaded regex_... requires
an additional step to extract the resulting values,
compare it to the original version:

bool TimeParser(cons t std::string& time, TIMESTRUCT& st)
{
using namespace boost;
cmatch m;
if(regex_match( time.c_str(), m, regex("^(\\d{2} ):(\\d{2})\\.(\ \d{2})$"))) {
st.Hour = atoi(m[1].first);
st.Minute = atoi(m[2].first);
st.Second = atoi(m[3].first);
return true;
}
return false;
}

Which looks (imho) less cluttered.
And since the expression is a constant, that's how I'd write it:
static regex const expr( "^(\\d{2}):(\\d {2})\\.(\\d{2}) $" ) ;
(at the start of the function, before the if).
This would, of course, be better from a technical point of view
but it costs one additional line ;-) But if you are paid for
LOCaday ...

Regards & thanks

M.
Jun 27 '08 #6

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

Similar topics

8
9449
by: Gerrit Holl | last post by:
Posted with permission from the author. I have some comments on this PEP, see the (coming) followup to this message. PEP: 321 Title: Date/Time Parsing and Formatting Version: $Revision: 1.3 $ Last-Modified: $Date: 2003/10/28 19:48:44 $ Author: A.M. Kuchling <amk@amk.ca> Status: Draft Type: Standards Track
2
3962
by: Cigdem | last post by:
Hello, I am trying to parse the XML files that the user selects(XML files are on anoher OS400 system called "wkdis3"). But i am permenantly getting that error: Directory0: \\wkdis3\ROOT\home Canonicalpath-Directory4: \\wkdis3\ROOT\home\bwe\ You selected the file named AAA.XML getXmlAlgorithmDocument(): IOException Not logged in
6
7660
by: BerkshireGuy | last post by:
Does anyone know of a good function that will parse out parts of an SQL statement that is passed to it in seperate variables? It should be able to parse statements that contain ORDERBY, WHERE, GROUP, etc. Thank you, Brian
9
1992
by: Paulers | last post by:
Hello, I have a log file that contains many multi-line messages. What is the best approach to take for extracting data out of each message and populating object properties to be stored in an ArrayList? I have tried looping through the logfile using regex, if statements and flags to find the start and end of each message but I do not see a good time in this process to create a new instance of my Message object. While messing around with...
3
3322
by: Anup Daware | last post by:
Hi Group, I am facing a strange problem here: I am trying to read xml response from a servlet using XmlTextWriter. I am able to read the read half of the xml and suddenly an exception: “Unexpected end of file while parsing Name has occurred†isbeing thrown. Following is the part o xml I am trying to read: <CHECK_ITEM_OUT>
3
2707
by: aspineux | last post by:
My goal is to write a parser for these imaginary string from the SMTP protocol, regarding RFC 821 and 1869. I'm a little flexible with the BNF from these RFC :-) Any comment ? tests= def RN(name, regex): """protect using () and give an optional name to a regex""" if name:
2
4889
by: RG | last post by:
I am having trouble parsing the data I need from a Serial Port Buffer. I am sending info to a microcontroller that is being echoed back that I need to remove before I start the actual important data reading. For instance this is my buffer string: 012301234FFFFFFxFFFFFFxFFFFFFx Where the FFFFFF is my Hex data I need to read. I am using the "x" as a separater as I was having problems using the VbCrLf. But I think
6
1928
by: gw7rib | last post by:
I have a program that needs to do a small amount of relatively simple parsing. The routines I've written work fine, but the code using them is a bit long-winded. I therefore had the idea of creating a class to do parsing. It could be used as follows: int a, n, x, y; Parser par; par << string;
1
2968
by: hd95 | last post by:
In a perfect world my xml feed source would produce perfect xml ..that is not the case I am parsing an XML feed that sometimes has ampersands and dashes in the content that messes up my parsing. I've tried doing pre processing with find/replace to get rid of these characters but then I get another type of error "An unexpected end of file parsing CDATA has occurred" So to get around that error I've added in unicoding and removing...
1
4411
by: eyeore | last post by:
Hello everyone my String reverse code works but my professor wants me to use pop top push or Stack code and parsing code could you please teach me how to make this code work with pop top push or Stack code and parsing code my professor i does not like me using buffer reader on my code and my professor did even give me an example code for parsing as well as pop push top or Stack code and i don't know how to do this code into parsing and pop push...
0
9727
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
9605
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
10647
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
10133
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
9204
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...
0
6889
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
5554
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...
1
4339
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
3
3017
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.