James Kanze
10/10/2008 9:06:00 PM
On Oct 10, 10:02 pm, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
> WP wrote:
> > Say I have string of the following form:
> > "integer stringpart". First an integer, then a space and
> > then the stringpart which may or may not contain additional
> > spaces. I wanted to separate the integer and the stringpart,
> > so I tried:
> > istringstream iss(str);
> > int num;
> > iss >> num;
> > Ok, now num contains the int-part. But how do I get the rest
> > into a string variable? iss.str() returns the entire string
> > and iss >> astrinvar; only gets me a subpart if the
> > stringpart contains spaces Is a loop my only option here or
> > have I missed something?
> You can always get the remaining part of the stringstream by
> reading its 'streambuf', I think:
That would be the a solution, I think, if you don't know a
character that can't be in the string. If you know that there's
no newline, however, getline will also work; if there is no
further white space, >> into a string is fine.
> #include <iostream>
> #include <sstream>
> #include <string>
> using namespace std;
> int main()
> {
> string str("123 abc");
> int a;
> istringstream is(str);
> is >> a;
> // here we extract a copy of the "remainder"
> string rem(is.str().substr(is.tellg()));
That's not what you said above, and I'm not sure what it will
give. Calling istringstream::str() seems very strange to me.
I'd prefer something like:
std::string remaining ;
is >> remaining ; // skips white space, stops at next
// following whitespace.
std::getline( is, remaining ) ;
// reads until next '\n'
std::ostringstream os ;
os << is.rdbuf() ; // gets absolutely everything.
Don't forget that istream::tellg() isn't guaranteed to be
convertible into an integral type, and even if it is, there is
no guarantee concerning the numeric value.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34