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.

This'd work.

string filepath;
getline(cin, filepath);
ifstream fis(filepath.c_str());

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.