简体   繁体   中英

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. 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 argument 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).

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM