By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,227 Members | 1,310 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,227 IT Pros & Developers. It's quick & easy.

Parsing a string into integers using istringstream

P: n/a
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
Share this Question
Share on Google+
2 Replies


P: n/a
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

P: n/a
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.