stringstream::seekp 2015 年 Visual Studio 无法运行

stringstream::seekp not functioning on Visual Studio 2015

我想从文件中读取一大块数据到stringstream,稍后将用于解析数据(使用getline、>>等)。读取字节后,我设置了字符串流的缓冲区,但我无法设置 p 指针。 我在一些在线服务上测试了代码,例如 onlinegdb.com 和 cppreference.com 并且它有效。但是,在 Microsoft 上,我得到一个错误 - 指针乱序。

这是代码,我用字符数组替换了文件读取。

#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;
}

我在工作时得到的输出

g 0 p 0
g 0 p 7

我在 visual studio 2015

上获得的输出
g 0 p 0
g -1 p -1

有什么想法吗?

谢谢

std::sstream::setbuf可能什么都不做:

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.

您最好使用 std::stringstream 构造函数来设置数据或调用 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;
}