Parse a string for integers

I have a string that holds a date in the format of "Year Day Step" That is, for example "2011 98 129300"
I want to take this line and assign the year/day/step as values to my Time class which is a struct with 3 unsigned integers: Year, Day and Step.

How do I take each chunk of characters seperated by space and assign as values to integers?
Have a look at the following:

1) Using insertion operator (<<) with stringstreams:
http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C/

2) Using extraction operator (>>) with stringstreams (for conversion):
http://www.cplusplus.com/reference/iostream/istream/operator%3E%3E/

Good luck.



Last edited on
I must be doing something wrong.

I can do this successfully for the first value, but I can't seem to make the 2nd and 3rd fields come out as anything but 0. I tried << with flush and I tried calling flush().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
World::Time::Time( const std::string& adate ):
	mYear(0), mDay(0), mStep(0){
	using namespace std;
	stringstream lconvert;
	Range lsub(0,0);
		assert( adate[0]!=' ' && adate[0]!='\n' );
		for( Uint i=0; i<adate.size(); ++i ){
		if( adate[i]==' ' ){
			lsub.y = i;
			break;
		}
	}
	lconvert << adate.substr( lsub.x, lsub.y-lsub.x );
	lconvert >> this->mYear;
	
	lsub.x = lsub.y+1;
		assert( adate[lsub.x]!=' ' && adate[lsub.x]!='\n' );
		for( Uint i=lsub.x; i<adate.size(); ++i ){
		if( adate[i]==' ' ){
			lsub.y = i;
			break;
		}
	}
	lconvert << adate.substr( lsub.x, lsub.y-lsub.x );
        lconvert >> this->mDay;
	lsub.x = lsub.y+1;
	lsub.y = adate.size()-1;
	assert( adate[lsub.x]!=' ' && adate[lsub.x]!='\n'
		&& adate[lsub.y]!=' ' && adate[lsub.y]!='\n' );
	lconvert << adate.substr( lsub.x, lsub.y-lsub.x );
	lconvert >> this->mStep;

}

Last edited on
¿what the hell is lsub, and what is it doing?
Think of an istringstream as any istream (like cin), when you read numbers it will ignore the spaces and line breaks.

Edit: actually there is a manipulator http://www.cplusplus.com/reference/iostream/manipulators/skipws/
Last edited on
thanks I'll take a look
(lsub is a range with x being the start of the number and y being the terminating space. I use it to send substrings to the stringstream with .substr( )
This works much better now :)
1
2
3
4
5
6
7
8
9
10
11
World::Time::Time( const std::string& adate ):
	mYear(0), mDay(0), mStep(0){
	using namespace std;
	stringstream lconvert;

	lconvert << adate;

	lconvert >> this->mYear;
	lconvert >> this->mDay;
        lconvert >> this->mStep;
}

Topic archived. No new replies allowed.