Reputation: 33813
See the example to understand
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
*/
Upvotes: 0
Views: 62
Reputation: 361302
Use std::stringstream
as:
#include <sstream> //include this
std::stringstream ss;
ss << Folder << rnd;
string final_name = ss.str();
Or you can write this just in one line:
string final_name = stringbuilder() << Folder << rnd;
All that it needs a small utility class:
struct stringbuilder
{
std::stringstream ss;
template<typename T>
stringbuilder & operator << (const T &data)
{
ss << data;
return *this;
}
operator std::string() { return ss.str(); }
};
Using this class, you can create std::string
on the fly as:
void f(const std::string & file ) {}
f(stringbuilder() << Folder << rnd);
std::string s = stringbuilder() << 25 << " is greater than " << 5 ;
Upvotes: 3
Reputation: 18064
Convert rnd
(it is in integer type) to string
type then do the same
string final_name = Folder + rnd;
Upvotes: -1
Reputation: 476950
Say this:
std::string final_name = Folder + std::to_string(rnd);
If you have an old compiler that doesn't support C++11, you can use boost::lexical_cast
, or std::snprintf
, or string streams.
Upvotes: 2
Reputation: 15165
In c++ you use stringstream to convert integers to strings.
int rnd = rand() %10;
string Folder = "c://foldername";
stringstream ss;
ss << Folder << rnd;
string final_name = ss.str(); // here the target
Upvotes: 2
Reputation: 35039
In C++ the best way to do this is to use a stringstream
:
#include<sstream>
...
std::stringstream stream;
stream << "c://foldername" << rand() %10;
stream.str(); // now contains both path and number
Upvotes: 2