jeudi 3 septembre 2020

Concatonating multiple strings to a c string [duplicate]

Let me start off by saying, I know it's not ideal. What am I doing using c strings with c++? Good question, but some of the old services for the software I work with don't store dynamic memory. That being said. I'm trying to solve a frequent issues of

  • conversions of string literals to char *
  • possible buffer overflows from c methods of concatenating strings.

I ran into issues with c strings. I found this thread which has a lot of great methods for taking a stream of string literals, integers, floats, whatever, and concatenating it into a string. For nearly any one of those examples, I can do something like this:

std::string s = stringger("word1", ' ', 12345, ' ', "word2");
const char *c = s.c_str();

Below is an example of what I am hoping to do. Once again, it compiles but returns nothing.

#include <iostream>
#include <string>
#include <sstream>

template< typename ... Args >
const char* stringer(Args const& ... args )
{
    std::ostringstream stream;
    using List= int[];
    (void)List{0, ( (void)(stream << args), 0 ) ... };

    return stream.str().c_str();
}

int main()
{
    const char *s = stringer("hello", ' ', 23, ' ', 3.14, " Bye! " );

    std::cout << s << '\n';

however, when I attempt to change the return type I get nothing. It compiles, but I assume it returns null. What am I missing?

Concatenation of strings thread.

Aucun commentaire:

Enregistrer un commentaire