0

i am new to c++ and wonder about how i create a file for example

string flight;
cin>>flight;
flight=flight+".txt";
ofstream myfile;
myfile.open(flight);
instead of having a fixed name like myfile.open("file.txt")

but it doesnt work , are there elegant solutions to this problem i have. all the help is appreciated.

4
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by mvmalderen
0

You could be missing headers. But also, you need to use the c_str() member of a string to open a file.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
    string flight;
    cin >> flight;
    flight = flight + ".txt";
    ofstream myfile;
    myfile.open (flight.c_str());
    myfile << "Hello there.\n";
    myfile.close();
}
0

Yup, fstream's open-method only accepts a c-string as it's argument for the filename, so you'll have to convert your C++ string to a c-string first, you can easily do this by using the c_str() method of the string class :) ...

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.