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

 ̄綄美尐妖づ 提交于 2019-12-06 16:47:56

问题


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 argument 1' toFILE* freopen(const char*, const char*, FILE*)'|

How I can solve this?


回答1:


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:

  • cppreference.com - std::basic_string::c_str



回答2:


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();



回答3:


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.



来源:https://stackoverflow.com/questions/11463674/trying-to-create-an-output-file-with-freopen-using-non-constant-string

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