Trying to create an output file with freopen, using non-constant string

左心房为你撑大大i 提交于 2019-12-04 21:52:31

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.


Examples and notes

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.


You can read more about the function if you follow the link below:

i have a small app that does this exactly. there are several ways to do this.. the simplest of which is

const char * newvar = stringname.c_str();
Jerry Coffin

If you're going to use sprintf, it's probably easiest to skip using std::string at all:

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::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++. It's generally better to write to an ostream. Answers to a previous question show how to connect cout to a different output file, if you truly need to.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!