469,636 Members | 1,516 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,636 developers. It's quick & easy.

Parsing a string into integers using istringstream

I want to parse a string (actually a date [always in the format
'YYYYMMDD') into integer values like this:

void parseDate(const string&sdate, int& day, int& mon, int &year)
{
istringstream iss(sdate) ;
....
}

I can do this easily in C (using atoi etc), but i wanted not too sure
how in C++.

Nov 6 '06 #1
2 3231
Bit Byte wrote:
I want to parse a string (actually a date [always in the format
'YYYYMMDD') into integer values like this:

void parseDate(const string&sdate, int& day, int& mon, int &year)
{
istringstream iss(sdate) ;
....
}

I can do this easily in C (using atoi etc), but i wanted not too sure
how in C++.
First you need to convert "YYYYMMDD" into components.

std::string date = "20061113";

// Take care to assert here if the string is not long enough.
assert( date.size() == 8 );

std::string year( date.begin(), date.begin() + 4 );

std::string month( date.begin() + 4, date.begin() + 6 );

std::string day( date.begin() + 6, date.end() );

Then you can convert each component.
Nov 6 '06 #2
Gianni Mariani wrote:
Bit Byte wrote:
I want to parse a string (actually a date [always in the format
'YYYYMMDD') into integer values like this:

void parseDate(const string&sdate, int& day, int& mon, int &year)
{
istringstream iss(sdate) ;
....
}

I can do this easily in C (using atoi etc), but i wanted not too
sure how in C++.

First you need to convert "YYYYMMDD" into components.

std::string date = "20061113";

// Take care to assert here if the string is not long enough.
assert( date.size() == 8 );

std::string year( date.begin(), date.begin() + 4 );

std::string month( date.begin() + 4, date.begin() + 6 );

std::string day( date.begin() + 6, date.end() );

Then you can convert each component.

Yikes. This is a case where'd I'd just use old-style:
sscanf(sdate.c_str(), "%4d%2d%2d", &year, &mon, &day);
There's probably some Boost thing that does something similar, but I
don't know anything about that.


Brian
Nov 6 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

10 posts views Thread by george young | last post: by
10 posts views Thread by Christopher Benson-Manica | last post: by
6 posts views Thread by Allan Bruce | last post: by
5 posts views Thread by Steve | last post: by
10 posts views Thread by Randy Yates | last post: by
1 post views Thread by Adam Parkin | last post: by
5 posts views Thread by tech | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.