How to put stringstream contents into char instead string type?

后端 未结 4 701
滥情空心
滥情空心 2021-01-17 21:10

Every one know stringstream.str() need a string variable type to store the content of stringstream.str() into it .

I want to store the cont

4条回答
  •  無奈伤痛
    2021-01-17 21:15

    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 
    #include 
    
    struct membuf: public std::streambuf {
        template  membuf(char (&array)[Size]) {
            this->setp(array, array + Size - 1);
            std::fill_n(array, Size, 0);
        }
    };
    
    struct omemstream: virtual membuf, std::ostream {
        template  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.

提交回复
热议问题