Every one know stringstream.str()
need a string variable type to store the content of stringstream.str()
into it .
I want to store the content of stringstream.str()
into char variable or char array or pointer.
Is it possible to do that?
Please, write a simple example with your answer.
A stringstream class in C++ is a Stream Class to Operate on strings. The stringstream class Implements the Input/Output Operations on Memory Bases streams i.e. string: The stringstream class in C++ allows a string object to be treated as a stream.
StringStream in C++ is similar to cin and cout streams and allows us to work with strings. Like other streams, we can perform read, write, and clear operations on a StringStream object. The standard methods used to perform these operations are defined in the StringStream class.
Absolutely! Make sure that you pass it by reference, not by value.
A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input.
If you want to get the data into a char
buffer, why not put it there immediately anyway? Here is a stream class which takes an array, determines its size, fills it with null characters (primarily to make sure the resulting string is null terminated), and then sets up an std::ostream
to write to this buffer directly.
#include <iostream>
#include <algorithm>
struct membuf: public std::streambuf {
template <size_t Size> membuf(char (&array)[Size]) {
this->setp(array, array + Size - 1);
std::fill_n(array, Size, 0);
}
};
struct omemstream: virtual membuf, std::ostream {
template <size_t Size> omemstream(char (&array)[Size]):
membuf(array),
std::ostream(this)
{
}
};
int main() {
char array[20];
omemstream out(array);
out << "hello, world";
std::cout << "the buffer contains '" << array << "'\n";
}
Obviously, this stream buffer and stream would probably live in a suitable namespace and would be implemented in some header (there isn't much point in putting anything of it into a C++ file because all the function are templates needing to instantiated). You could also use the [deprecated] class std::ostrstream
to do something similar but it is so easy to create a custom stream that it may not worth bothering.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With