0

Basically I want to be able to create a file name using two variables defined during the program (value unknown to programmer). I can do it using just one variable (i.e (username + ".txt")) , but for some reason using two messes it up.

This is my code.

void User::setTicket(std::string username, int i)
{
    std::ofstream fout (username + "Ticket" + i + ".txt");

    // Some code

        fout.close();
}

int i is essentially a counting digit initialised in a loop in main, so everytime the loop goes round setTicket is called, and hopefully the resulting files would be called

user1Ticket1.txt
user1Ticket2.txt
user1Ticket3.txt
etc

user3001499
  • 811
  • 4
  • 16
  • 32

3 Answers3

3

Numerical types can't be implicitly converted to, or directly appended to, strings.

In C++11 or later, there's a library function to convert them:

std::ofstream fout (username + "Ticket" + std::to_string(i) + ".txt");

Historically, string-streams can build strings from arbitrary types:

std::ostringstream ss;
ss << username << "Ticket" << i << ".txt";
std::ofstream fout (ss.str().c_str());
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
2

You have to convert the integer to a string using std::to_string(i) (c++11) in order to use operator + of a string

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

1

Basically, there are 3 ways to do it.

In case you have a c++11 compiler, you can the std::to_string(i), as @Dlotan pointed:

std::ofstream fout(username + "Ticket" + std::to_string(i) + ".txt");

In case you want to use boost:

std::ofstream fout(username + "Ticket" + boost::lexical_cast<std::string>(i) + ".txt");

In case you don't have a c++11 compiler neither want to use boost:

stringstream ss;
ss << i;
std::ofstream fout(username + "Ticket" + ss.str() + ".txt");
Hugo Corrá
  • 14,546
  • 3
  • 27
  • 39