1

I have a function which takes a const char* argument. I need to concatenate two string literals and an int to pass to this argument. Basically this is what I'm trying to do:

open(const char* filename) {}

void loadFile(int fileID)
{
    open("file" + fileID + ".xml");
}

int main()
{
    loadFile(1);
    return 0;
}

How can I make this work as simply as possible? I tried changing the loadFile function to take a const char* and then doing open(std::string("file").c_str() + fileID + std::string(".xml").c_str()); but then I get error: invalid operands of types 'const char*' and 'const char*' to binary 'operator+' so I'm pretty lost.

Mike
  • 587
  • 1
  • 6
  • 11

5 Answers5

4

You need to use something like:

std::ostringstream os;
os << "file" << fileID << ".xml";
open(os.str().c_str());
Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
4

You can use the stringstream as stated before or Boost format:

#include <boost/format.hpp>

void loadFile(int fileID)
{
  std::string filename = (boost::format("File%d.xml") % fileID).str();
  open(filename.c_str();
}
Johan
  • 3,728
  • 16
  • 25
2

If your compiler supports C++11, you can use std::to_string to get a string representation of a number:

std::string filename = "file" + std::to_string(fileId) + ".xml";

However, if you have Boost available, I think using Boost format, as discussed in Johan's answer, is more readable.

Chris W.
  • 927
  • 8
  • 16
  • Chosen because I can keep everything within the function call, `open(std::string("file" + std::to_string(fileID) + ".xml").c_str());` which is exactly my goal. – Mike Nov 17 '13 at 20:59
0

Use to_string()

open("file" + to_string(fileID) + ".xml");
Parag
  • 662
  • 9
  • 15
0

C++ is a superset of c. You could use sprintf:

void loadFile(unsigned int fileID)
{
   const int BUFFER_SIZE = 128;
   char buffer[BUFFER_SIZE];
   sprintf(buffer,"file%u.xml");
   open(buffer);
}

This is portable, should be safe for all passed in (uint) values, etc.

You can also use snprintf(buffer,BUFFER_SIZE,....) if you are concerned about overrunning the buffer.

FuzzyBunnySlippers
  • 3,387
  • 2
  • 18
  • 28