尝试使用非恒定字符串使用freopen创建输出文件 [英] Trying to create an output file with freopen, using non-constant string
问题描述
我正试图创建一个文件,其名称为字符串常量,但由常量字符串"List"组成的字符串为整数+扩展名.这是我的代码:
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:
错误:无法将
std::string' to
const char *'转换为参数1' to
FILE * freopen(const char *,const char *,FILE *)'|
error: cannot convert
std::string' to
const char*' for argument1' to
FILE* freopen(const char*, const char*, FILE*)'|
我该如何解决?
推荐答案
由于编译器错误指出,没有从std::string
到char const*
的隐式转换(即 c-style-string >在这种情况下.
As the compiler error states there is no implicit conversion from std::string
to char const*
(ie. a c-style-string in this context).
Though std::string
has a member-function named c_str
which will generate a null-terminated string and return a pointer to it that is very usable when dealing with legacy C functions.
freopen (result.c_str (), "w", stdout);
char const * p = result.c_str ();
请注意,如果您对托管对象(在本例中为result
)进行任何修改,则std::string::c_str
指向的 c-style-string 将失效.将返回的值存储在非临时变量中通常是不明智的.
Please note that the c-style-string pointed towards by std::string::c_str
will be invalidated if you make any modifications to the hosting object (in this case result
), therefore it is normally not wise to store the value returned in a non-temporary variable.
如果您点击以下链接,则可以阅读有关该功能的更多信息:
这篇关于尝试使用非恒定字符串使用freopen创建输出文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!