简体   繁体   English

如何在没有c ++副本的情况下从ostringstream获取char指针

[英]how to get char pointer from ostringstream without a copy in c++

I have a ostringstream variable which contains some data. 我有一个包含一些数据的ostringstream变量。 I want to get set a char * pointer to the data inside the ostringstream. 我想设置一个指向ostringstream内部数据的char *指针。

If I do the following: 如果我执行以下操作:

std::ostringstream ofs;
.....
const char *stam = (ofs.str()).c_str();

There is a copy of the content of the string in ofs. 在ofs中有一个字符串内容的副本。 I want to get a pointer to that content without a copy. 我希望得到一个没有副本的指向该内容的指针。

Is there a way to do so? 有办法吗?

This actually answers the question... took a while but I wanted to do it for the same reasons (efficiency vs portability is fine for my situation): 这实际上回答了这个问题...花了一段时间,但我想这样做是出于同样的原因(效率与便携性对我的情况很好):

class mybuf : public std::stringbuf {
public:
    // expose the terribly named end/begin pointers
    char *eback() {
        return std::streambuf::eback();
    }
    char *pptr() {
        return std::streambuf::pptr();
    }
};


class myos : public std::ostringstream {
    mybuf d_buf;
public:
    myos() {
        // replace buffer
        std::basic_ostream<char>::rdbuf(&d_buf);
    }
    char *ptr();
};

char *myos::ptr() {
    // assert contiguous
    assert (  tellp() == (d_buf.pptr()-d_buf.eback()) );
    return d_buf.eback();
}

int main() {
    myos os;
    os << "hello";
    std::cout << "size: " << os.tellp()  << std::endl;
    std::string dat(os.ptr(),os.tellp());
    std::cout << "data: " << dat  << std::endl;
}

This points to, yet again, the deeper, underlying problem with the standard library - a confusion between contracts and "safety". 这又指出了标准库的深层次潜在问题 - 合同与“安全”之间的混淆。 When writing a messaging service, I need a library with efficient contracts... not safety. 在编写消息服务时,我需要一个有效合同的库...而不是安全。 Other times, when writing a UI, I want strong safety - and cares less about efficiency. 其他时候,在编写用户界面时,我需要强大的安全性 - 并且不太关心效率。

Although you can't get a pointer to the character buffer in the ostringstream, you can get access to its characters without copying them if you switch to using stringstream. 虽然你无法获得指向ostringstream中字符缓冲区的指针,但是如果你切换到使用stringstream,你可以访问它的字符而不复制它们。 A stringstream allows input and output (reading from and writing to the stream), whereas ostringstream allows only output (writing to the stream). 字符串流允许输入和输出(读取和写入流),而ostringstream仅允许输出(写入流)。 Example: 例:

std::stringstream ss;
ss << "This is a test.";

// Read stringstream from index 0.  Use different values to look at any character index.
ss.seekg(0);

char ch;
while (ss.get(ch)) {                  // loop getting single characters
    std::cout << ch;
}

ss.clear(); // Clear eof bit in case you want to read more from ss

This site has a pretty good overview of stringstreams and what you can do with them. 这个网站非常好地概述了字符串流以及你可以用它们做些什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM