Click to See Complete Forum and Search --> : Read specified number of char from istream


Jin Song
July 10th, 2002, 09:00 PM
Hi,

What is the most efficient way to read specified number (n) of characters from an istream to a std::string?

Thanks.

dude_1967
July 11th, 2002, 04:23 AM
Set the field width for input, read the string, set the string to the just-read-in input.

Chris.

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

void read_it(void)
{
char buffer[81];
cin >> setw(sizeof(buffer) / sizeof(char)) >> buffer;
string the_string = buffer;
}

int main(int argc, char* argv[])
{
read_it();

return 1;
}

:)

sandodo
July 11th, 2002, 04:46 AM
to read the char from the istream,
you can use like the following:

istream in;
streambuf* p = in.rdbuf()
std:string += p->sgetc()


or you can use p->sbumpc() to get the char too.
the difference between sgetc() and sbumpc() is that:
sgetc() return the current read char but donot move to next position, while sbumpc() will move to next position.

zdf
July 11th, 2002, 05:56 AM
I don't know much about stl, so please double-check.


void read( string& dst, int count, istream& is )
{
dst.resize(count, 0);
is.read( dst.begin(), count );
}

// usage
string s;
read(s, 10, cin);



Regards,

Jin Song
July 11th, 2002, 09:23 AM
This is what I need. Thanks.