Monday, May 5, 2008

Day 6 - Solution

The problem here is to break the string into corresponding numbers.

There are 2 general ways of going about it.

1. Using String Streams.
String Streams are a mechanism of converting a string to a stream. So you can do things like write to the stream and read from the stream, very similar to how you use cout and the << operator to write to Standard Output Stream and cin and >> operator to read from the Standard Input Stream.

So we initialize a String Stream with our string - namely DOB.
We then read the day, the '/' character, the month, the '/' character and the year from it.

Check the Program.


Click on the image for a clearer view.


2. The 2nd way is using sscanf()
The syntax of sscanf is very similar to scanf, only that you need to specify the string that it needs to scan as the first argument. Note that sscanf() is a C compatible function so our string object (dob) won't work with it. We will have to convert it to a C compatible string. That is attained by using the c_str() functionality built in the string class.
eg string obj -> "12/3/00"
obj.c_str() => char * => "12/3/00\0"

You'll understand better by having a look at the program.



Click on the image for a clearer view.


The result of both the program is the same:-



If you know of any other ways, please bring it to my notice :)

No comments: