Patryk
Patryk

Reputation: 24092

Open file with filename as variable

I want to create files with names composed of int variables + ".txt". I have already tried this :

std::string filename = i + ".txt";

sprintf is not the best way - at least in my opinion as it requires a C style string with allocated memory

sprintf( tmp, "%d.txt", i);
std::string filename = tmp;

Maybe itoa is the best choice ?

Upvotes: 2

Views: 1776

Answers (3)

Alastair Taylor
Alastair Taylor

Reputation: 425

If you are using C++11 you can simply use

std::to_string

http://en.cppreference.com/w/cpp/string/basic_string/to_string

Upvotes: 0

Joe
Joe

Reputation: 57179

You can use a stringstream

#include <sstream>

...
    std::stringstream ss;
    ss << i << ".txt";

    std::string filename = ss.str();

Upvotes: 5

juergen d
juergen d

Reputation: 204766

std::stringstream fn;
fn << i << ".txt";
std::string filename = fn.str();

Upvotes: 3

Related Questions