Use stringstreams. They'll make the solution almost trivial.