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

时间:2011-10-18 11:53:26

标签: c++

请参阅示例以了解

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
*/

5 个答案:

答案 0 :(得分:3)

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 ;

答案 1 :(得分:2)

在C ++中,最好的方法是使用stringstream

#include<sstream>

...

std::stringstream stream;
stream << "c://foldername" << rand() %10;
stream.str(); // now contains both path and number

答案 2 :(得分:2)

在c ++中,您使用stringstream将整数转换为字符串。

int rnd = rand() %10;
string Folder = "c://foldername";
stringstream ss;
ss << Folder << rnd;
string final_name = ss.str(); // here the target

答案 3 :(得分:2)

说出来:

std::string final_name = Folder + std::to_string(rnd);

如果您的旧编译器不支持C ++ 11,则可以使用boost::lexical_caststd::snprintf或字符串流。

答案 4 :(得分:-1)

rnd(整数类型)转换为string类型,然后执行相同的操作

string final_name = Folder + rnd;