Parsing a string into integers using istringstream

B

Bit Byte

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++.
 
G

Gianni Mariani

Bit said:
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.
 
D

Default User

Gianni said:
Bit said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,243
Members
46,838
Latest member
KandiceChi

Latest Threads

Top