C++ – Optimal way to get a string or char* into an istream


What is the most optimal way to get a string or char* pointer into an istream.

I want to do the following

std::string a = "abc..";

//I know this can be done, not sure if this is most efficient
// and not sure about char*    pointers
std::istringstream istr (a);
foo (istr); 

void foo(std::istream& is) {


Best Answer

If you want to construct an istringstream from it, a char* up to the null character, or all the stuff from an std::string:

istringstream str(ptr); // char*
istringstream str(other_str); // std::string

If you talk about wanting a raw pointer into the buffer of an istream, you can't do it. Streams get their data on-demand if they need them either from files, terminals or else, optionally buffering their stuff (well, not exactly right. You can use a strstream, which accepts a raw pointer and reads/writes directly from that. But it's a deprecated class - don't use it. I'm lucky i've never done so). If all you want is something you can use somewhat like a pointer, you can use streambuf iterators. They are not really pointers though, so you can't subtract end from begin and other stuffs:

std::istreambuf_iterator<char> begin(one_istream), end;
while(begin != end)
    std::cout << *begin++;

If you talk about getting a string out of what was written into a stringstream, you can use ostringstream::str:

ostringstream o;
o << "This is a number: " << 42;
std::string str = o.str(); // str == "This is a number: 42"

Otherwise, you can only generally read stuff from an istream. You need an ostream, then you can do

stream.write(ptr, N);
stream.write(ptr.c_str(), ptr.c_str() + ptr.size());

to write exactly N characters from the bytes that str points to. You can write it into the stream using << too. It will write everything up to the null character, or everything from an std::string, but will respect formatting flags, like the field width:

stream << ptr; // char*
stream << other_str; // everything from std::string