0

I want to read a chunk of data from file into stringstream, which later will be used to parse the data (using getline, >>, etc). After reading the bytes, I set the buffer of the stringstream, but I cant make it to set the p pointer. I tested the code on some online services, such as onlinegdb.com and cppreference.com and it works. However, on microsoft, I get an error - the pointers get out of order.

Here's the code, I replaced the file-read with a char array.

#include <sstream>
#include <iostream>

int main()
{
    char* a = new char [30];
    for (int i=0;i<30;i++)
        a[i]='-';
    std::stringstream os;
    std::cout << "g " << os.tellg() << " p " << os.tellp() << std::endl;
    os.rdbuf()->pubsetbuf(a,30);
    os.seekp(7);
    std::cout << "g " << os.tellg() << " p " << os.tellp() << std::endl;
}

the output I get when it works

g 0 p 0
g 0 p 7

the output I get on visual studio 2015

g 0 p 0
g -1 p -1

any ides?

thanks

tamir
  • 81
  • 2
  • 9
  • I'm not sure an implementation is required to do anything when `setbuf()` is called. Can't you use `os.str(new_str)` (or `write()`) to set it instead? – Hasturkun Nov 06 '18 at 08:19
  • possible duplicate: https://stackoverflow.com/questions/12481463/stringstream-rdbuf-pubsetbuf-is-not-setting-the-buffer – marcinj Nov 06 '18 at 08:26
  • Possible duplicate of [stringstream->rdbuf()->pubsetbuf is not setting the buffer](https://stackoverflow.com/questions/12481463/stringstream-rdbuf-pubsetbuf-is-not-setting-the-buffer) – Alan Birtles Nov 06 '18 at 08:31

1 Answers1

1

std::sstream::setbuf may do nothing:

If s is a null pointer and n is zero, this function has no effect.

Otherwise, the effect is implementation-defined: some implementations do nothing, while some implementations clear the std::string member currently used as the buffer and begin using the user-supplied character array of size n, whose first element is pointed to by s, as the buffer and the input/output character sequence.

You are better off using the std::stringstream constructor to set the data or call str():

#include <sstream>
#include <iostream>

int main()
{
    std::string str( 30, '-' );
    std::stringstream os;
    std::cout << "g " << os.tellg() << " p " << os.tellp() << std::endl;
    os.str( str );
    os.seekp(7);
    std::cout << "g " << os.tellg() << " p " << os.tellp() << std::endl;
}
Community
  • 1
  • 1
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60