Setting mininum string read width in istream

R

Richard Clay

It seems odd that there is (apparently) no way of telling the istreamfirst space.

What I want to do is this:

string source("7 one two 5 fruit 3 tea 6 banana");
istringstream iss(source);
int strLen;
iss >> strLen; // get length of next string, 7 in first case
iss.force_next_string_read_to_be_this_length(strLen);
string s;
iss >> s; // s = "one two" in first case

Any elegant solutions? Don't think so - iss.width() is all about
maximum lengths, not minimum.
 
R

richard

Richard said:
It seems odd that there is (apparently) no way of telling the istream
first space.

What I want to do is this:

string source("7 one two 5 fruit 3 tea 6 banana");
istringstream iss(source);
int strLen;
iss >> strLen; // get length of next string, 7 in first case
iss.force_next_string_read_to_be_this_length(strLen);
string s;
iss >> s; // s = "one two" in first case

Slighly ugly, but how about:

vector<char> buf( strLen+1, '\0' );
size_t realLen = buf.get( &*s.begin(), s.size() );
string s( buf.begin(), buf.begin() + realLen );
 
M

Malte Starostik

Slighly ugly, but how about:

vector<char> buf( strLen+1, '\0' );
size_t realLen = buf.get( &*s.begin(), s.size() );
string s( buf.begin(), buf.begin() + realLen );
Perhaps slightly less ugly:
string s( strLen, 0 );
size_t realLen = buf.get( &s[ 0 ], s.size() );
s.resize( realLen );

Cheers,
Malte
 

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,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top