[英]Trying to create an output file with freopen, using non-constant string
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. 我正在尝试创建一个名称为字符串常量,但由常量字符串“ List”组成的字符串,该字符串为整数+扩展名。 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' to
const char*' for argument1' to
FILE* freopen(const char*, const char*, FILE*)'| 错误:无法将参数1' to
std::string' to
转换std::string' to
const char *'1' to
FILE * freopen(const char *,const char *,FILE *)'|
How I can solve this? 我该如何解决?
As the compiler error states there is no implicit conversion from std::string
to char const*
(ie. a c-style-string in this context). 由于编译器错误指出,没有从std::string
到char const*
隐式转换(即,在这种情况下为c样式字符串 )。
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. 尽管std::string
有一个名为c_str
的成员函数 ,它将生成一个以空值结尾的字符串,并返回一个指向它的指针,这在处理旧版C函数时非常有用。
freopen (result.c_str (), "w", stdout);
char const * p = result.c_str ();
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. 请注意,如果您对托管对象进行任何修改(在本例中为result
),则std::string::c_str
指向的c-style-string将无效,因此,通常不明智的做法是将返回的值存储在非临时变量。
You can read more about the function if you follow the link below : 如果您点击以下链接,则可以阅读有关该功能的更多信息 :
If you're going to use sprintf
, it's probably easiest to skip using std::string
at all: 如果要使用sprintf
,则可能最容易跳过使用std::string
的操作:
char name[32];
sprintf(name, "lista%d.txt", cont);
freopen(name, "w", stdout);
If you're going to use std::string
(probably preferable for most C++ anyway), you probably want to use std::stringstream
to create the name: 如果要使用std::string
(无论如何,对于大多数C ++来说可能更可取),则可能要使用std::stringstream
创建名称:
std::ostringstream name;
name << "lista" << cont << ".txt";
freopen(name.str().c_str(), "w", stdout);
However, I'd tend to avoid freopen
in general, and avoid using C-style streams (such as stout) in C++. 但是,我通常倾向于避免使用freopen
, 并避免在C ++中使用C样式的流(例如stout)。 It's generally better to write to an ostream
. 通常最好写一个ostream
。 Answers to a previous question show how to connect cout
to a different output file, if you truly need to. 上一个问题的答案显示了如果确实需要,如何将cout
连接到另一个输出文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.