Home > front end >  Function or library to create strings from every primitive data type and String?
Function or library to create strings from every primitive data type and String?

Time:04-03

Is there a function to create strings or char[] by concatenating multiple types?

Something like:

int int_type = 5;
float float_type = 3.14;
String string_type = "I'm";
char char_type = ' ';
char char_arr_type[9] = "a pirate"; 

String merged = x_func(int_type, float_type, string_type, char_type, char_arr_type);

// expected: "53.14I'm a pirate"

CodePudding user response:

in c 17 you can use fold expression and string stream.

Example:

#include <iostream>
#include <sstream>
using namespace std;

template<typename ... Args>
string makeString(Args ... args)
{   
    stringstream ss;
    (ss << ... << args);
    return ss.str();
}
int main(){
    cout<< makeString("a b" , 1, "c d");
}

Output: a b1c d

CodePudding user response:

You can use a std::stringstream for this purpose. It works almost the same way as printing all the variables to std::cout. Example:

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

int main() 
{
    // Your variables
    int int_type = 5;
    float float_type = 3.14;
    std::string string_type = "I'm";
    char char_type = ' ';
    char char_arr_type[9] = "a pirate"; 

    // Creating a new stream
    std::stringstream s;
    
    // Print all the variables to the stream
    s << int_type << float_type << string_type << char_type << char_arr_type;
    
    // retrieve the result as std::string
    std::string merged = s.str();
    
    std::cout << merged; // output: 53.14I'm a pirate
}

PS: I'm not sure what String in your code means, C only has std::string. Unless this is a typo you might have to do some casting or provide a custom operator<<(std::ostream&, const String&).

CodePudding user response:

In C 20 and later, you can use std::format():

std::string merged = std::format("{}{}{}{}{}", int_type, float_type, string_type, char_type, char_arr_type);

In C 11 and later, you can use the {fmt} library instead.

  •  Tags:  
  • c
  • Related