是否有通過連接多種型別來創建字串或 char[] 的函式?
就像是:
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"
uj5u.com熱心網友回復:
std::stringstream為此,您可以使用 a 。它的作業方式幾乎與將所有變數列印到std::cout. 例子:
#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:我不確定String你的代碼是什么意思,C 只有std::string. 除非這是一個錯字,否則您可能必須進行一些轉換或提供自定義operator<<(std::ostream&, const String&).
uj5u.com熱心網友回復:
在 C 20 及更高版本中,您可以使用std::format():
std::string merged = std::format("{}{}{}{}{}", int_type, float_type, string_type, char_type, char_arr_type);
在 C 11 及更高版本中,您可以改用{fmt} 庫。
uj5u.com熱心網友回復:
在 c 17 中,您可以使用折疊運算式和字串流。
例子:
#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");
}
輸出:a b1c d
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/455261.html
標籤:C
