【问题标题】:stringstream::seekp not functioning on Visual Studio 2015stringstream::seekp 在 Visual Studio 2015 上不起作用
【发布时间】:2018-11-06 08:00:39
【问题描述】:

我想从文件中读取一块数据到字符串流中,稍后将用于解析数据(使用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

有什么想法吗?

谢谢

【问题讨论】:

标签: c++ visual-studio-2015 iostream stringstream


【解决方案1】:

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

如果 s 为空指针且 n 为零,则此函数无效。

否则,效果是实现定义的:一些实现什么都不做,而一些实现清除当前用作缓冲区的 std::string 成员并开始使用用户提供的大小为 n 的字符数组,其第一个元素被指向to by s,作为缓冲区和输入/输出字符序列。

你最好使用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;
}

【讨论】:

    猜你喜欢
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多