Reputation: 529
I am trying to use a variable in my file path.
I have succeeded in adding one for the name of the files, but not for the folder name.
string utilisateur, mot_de_passe;
int gr;
cout << " Entrer un nom utilisateur:"; cin >> utilisateur;
cout << " Entrer un mot de passe :"; cin >> mot_de_passe;
cout << "Choisir un groupe:"; cin >> gr;
ofstream dossier;
if (gr == 1)
{
dossier.open("C:/Users/titib/Contacts/Desktop/Projet informatique/groupe/" + utilisateur + ".txt");
dossier << utilisateur << endl << mot_de_passe << endl << gr << endl;
I would like to use the variable gr
as the name of the folder.
dossier.open("C:/Users/titib/Contacts/Desktop/Projet informatique/groupe/**gr**" + utilisateur + ".txt");
Upvotes: 4
Views: 3579
Reputation: 529
Okay i finnaly succeed to create a file. Thanks to Remy Lebeau.
Actually i changed few things :
i used filedirectory . Here the code
std::ostringstream gr;
gr << "C:/Users/titib/Contacts/Desktop/Projet informatique/" << groupe;
CreateDirectory(gr.str().c_str(), NULL);
dossier.open("C:/Users/titib/Contacts/Desktop/Projet informatique/" + groupe + "/" + utilisateur + ".txt");
dossier << utilisateur << endl << mot_de_passe << endl << groupe << endl;
Thanks again.
Upvotes: 0
Reputation: 596352
You need to convert gr
to a std::string
before you can append it to another string. Prior to C++11, you can use std::ostringstream
for that, eg:
#include <sstream>
std::ostringstream oss_gr;
oss_gr << gr;
dossier.open("C:/Users/titib/Contacts/Desktop/Projet informatique/groupe/" + oss_gr.str() + "/" + utilisateur + ".txt");
Or, if you are using C++11 or later, you can use std::to_string()
instead:
dossier.open("C:/Users/titib/Contacts/Desktop/Projet informatique/groupe/" + std::to_string(gr) + "/" + utilisateur + ".txt");
Alternatively, in any C++ version, you could use std::ostringstring
to format the entire path instead:
std::ostringstream oss_path;
oss_path << "C:/Users/titib/Contacts/Desktop/Projet informatique/groupe/" << gr << "/" << utilisateur << ".txt";
dossier.open(oss_path.str());
Upvotes: 1
Reputation: 9407
This should work just fine:
std::string FilePath = "C:/Users/titib/Contacts/Desktop/Projet informatique/groupe/" + std::to_string(gr) + "/" + utilisateur + ".txt";
dossier.open(FilePath);
Upvotes: 2