I’m trying to create a file whose name is a string constant, but a string consisting of a constant string “List” an integer + + an extension. Here’s my code:
#include <iostream>
#include <vector>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main (){
int cont=0;
std::string result;
std::string name = "Lista";
std::string ext = ".txt";
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", cont);
result = name + numstr+ext;
freopen (result, "w", stdout);
cout<<result<<endl;
return 0;
}
When I try to build tells me the following error:
error: cannot convert
std::string' toconst char*’ for argument1'FILE* freopen(const char*, const char*, FILE*)’|
to
How I can solve this?
As the compiler error states there is no implicit conversion from
std::stringtochar const*(ie. a c-style-string in this context).Though
std::stringhas a member-function namedc_strwhich will generate a null-terminated string and return a pointer to it that is very usable when dealing with legacy C functions.Examples and notes
Please note that the c-style-string pointed towards by
std::string::c_strwill be invalidated if you make any modifications to the hosting object (in this caseresult), therefore it is normally not wise to store the value returned in a non-temporary variable.You can read more about the function if you follow the link below: