gpt4 book ai didi

c++ - 如何在其他变量中加入2个变量

转载 作者:太空宇宙 更新时间:2023-11-04 15:08:37 24 4
gpt4 key购买 nike

看例子理解

int rnd = rand() %10;
string Folder = "c://foldername";
string final_name = Folder + rnd; // here the target

/* I want the result like that (random folder name)
foldername5
foldername10
foldername3
foldername20
foldername17
*/

最佳答案

std::stringstream 用作:

#include <sstream> //include this

std::stringstream ss;
ss << Folder << rnd;
string final_name = ss.str();

或者你可以只写一行:

string final_name = stringbuilder() << Folder  << rnd;

它需要一个小的实用类:

struct stringbuilder
{
std::stringstream ss;
template<typename T>
stringbuilder & operator << (const T &data)
{
ss << data;
return *this;
}
operator std::string() { return ss.str(); }
};

使用这个类,你可以创建 std::string 作为:

void f(const std::string & file ) {}

f(stringbuilder() << Folder << rnd);

std::string s = stringbuilder() << 25 << " is greater than " << 5 ;

关于c++ - 如何在其他变量中加入2个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7806771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com