This question already has an answer here:
- How to concatenate a std::string and an int? 29 answers
I'm new to C++ and working on a simple project. Basically where I'm encountering a problem is creating a file with a number (int) in the file name. As I see it,I have to first convert the int to a string (or char array) and then concatenate this new string with the rest of the file name.
Here is my code so far that fails to compile:
int n; //int to include in filename
char buffer [33];
itoa(n, buffer, 10);
string nStr = string(buffer);
ofstream resultsFile;
resultsFile.open(string("File - ") + nStr + string(".txt"));
This gives a couple compilation errors (compiling in Linux):
- itoa not declared in this scope
- no matching function for call to ‘std::basic_ofstream char, std::char_traits char ::open(std::basic_string char, std::char_traits char , std::allocator char )’
I've tried the advice here: c string and int concatenation and here: Easiest way to convert int to string in C++ with no luck.
If I using the to_string method, I end up with the error "to_string not a member of std".
You can use
std::stringstream
Since the constructor requires a char pointer, you need to convert it into a char pointer using
Using
std::ostringstream
:Using
std::to_string
(C++11):You want to use
boost::lexical_cast
. You also need to include any needed headers:then it's simply:
because
std::strng
plays nicely with string literals (e.g. ".txt").You could use a
stringstream
to construct the filename.For
itoa
, you are likely missing#include <stdlib.h>
. Note thatitoa
is non-standard: the standard ways to format an integer as string assprintf
andstd::ostringstream
.ofstream.open()
takes aconst char*
, notstd::string
. Use.c_str()
method to obtain the former from the latter.Putting it together, you are looking for something like this:
for itoa function
consider this link
http://www.cplusplus.com/reference/cstdlib/itoa/