ostringstream operator[] giving compile error when trying to read buffer

131 Views Asked by At

I have a class that extends ostringstream class.

Class A: public ostringstream
{

}

I want to read data of specified size and a specific offset from that object. So trying:

A a_;
a_ << data1 << data2;
string datax(a_[offset], size);

But getting a compile error at string datax statement.

error: no match for operator[] in ... 

How can I copy data from object a_ for a specified offset and size? I dont want to remove data from the object a_.

NOTE: The class was designed by someone else and cannot be modified.

3

There are 3 best solutions below

1
On BEST ANSWER

I believe with the code you have you could do:

a_ << data1 << data2;
string datax(&a_.str()[offset], size);

which looks a bit ugly to me. Why not just use plain std::stringstream instead? (unless you have a strong reason to inherit from std::ostringstream.

0
On

First of all, nothing in the standard guarantees you that deriving from std::ostringstream will work. You'd be better not doing it at all.

Second, there is no operator [] for std::ostringstream so why should there be one for A?

Finally, you can call str() on a_ and get an std::string with the contents of the buffer. I'm not sure if that would help you, what you want to do is not entirely clear.

0
On

You need to call to str() method:

ostringstream oss (ostringstream::out);
oss << "abcdef";
string s = oss.str();
cout << s.substr(1, 3) << endl;

This example would output "bcd".