tags:

views:

274

answers:

1

I want to implement the following have a character buffer and the code I am trying to port puts this character buffer in a stream and then does a get like this

 char *buffer; //this is initialized
 int bufferSize;  //this is initlized
 std::istringstream inputStream (std::string(buffer, bufferSize));
 int getVal = inputStream.get();

EDIT: Is the above code optimal, wherein for getVal you copy the entire buffer to a stream and then do a get on the stream.

How can I get the getVal value from the buffer itself.

+1  A: 

I don't believe it's optimal, simply because constructing a std::string will likely cause a copy on the whole buffer. The istringstream usage, however, looks fine.

To get directly from the buffer you could do something like this:

int bufferPos = 0;

char getFromBuffer ()
{
  if (bufferPos < bufferSize)
  {
    return buffer[bufferPos++];
  }
  else
  {
    return 0;
  }
}

You may want to put a better interface on this, though. There may be a better way to construct an istringstream with a char* also, but I didn't see one while quickly browsing the docs.

Dan Olson
Minor nitpick: Shouldn't get() return -1 on EOF?
Mr.Ree