Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put stringstream contents into char instead string type?

Tags:

c++

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.

like image 214
Lion King Avatar asked Jan 06 '12 22:01

Lion King


People also ask

Is Stringstream a string?

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.

Can we use Stringstream in C?

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.

Can you pass a Stringstream in C++?

Absolutely! Make sure that you pass it by reference, not by value.

What is the use of Stringstream in C++?

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.


1 Answers

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.

like image 87
Dietmar Kühl Avatar answered Nov 10 '22 00:11

Dietmar Kühl