Save a file in a different directory (input name) C++

I need save a file in a different location but the file is not a default name that will be put in there it is a name that the user will assign to the document: (This is not the all the program it is just part of it)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
     string file;
    string txt = ".txt";
    
    ofstream outfile; 

   
    cout << "Please, enter the name for your output file: ";
    getline(cin, file);
    
  
    file += txt;
    outfile.open("C:/Users/contr/Documents/Custom Office Templates/file.c_str()");       
                                //Here is were the file wont be save as the 
                                //user was ask for it will will be file.c_str()        
                          
    outfile.close();                              
   
    cout << "\nProccessing your request\n";
    cout << "The program has saved the file as: " 
         << file << endl << endl; 




Thank you
Last edited on
You've literally named the file "file.c_str()".

What you need to do is take the string that contains the name the user has typed, and call the c_str() on that string.
right, so it when i do it like that but there is not going to the place where i need it to go to.

outfile.open(file.c_str());
1
2
3
string file_path("C:/Users/contr/Documents/Custom Office Templates/");
file_path += file.c_str();
outfile.open(file_path);
You have to concatenate the value contained in file to the path you want it to go into.

The easiest way that I can think of is to create a new string to contain the path and the append the file name. Then use the new string to open the file.

1
2
3
std::string path = "C:/Users/contr/Documents/Custom Office Templates/";
path += file;
outfile.open(path.c_str());
Thank you both of you (:
Last edited on
Topic archived. No new replies allowed.