Path to variable file inside C ++

I am trying to use a variable in my file path.

I managed to add one for the file name, 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 gras the name of the folder.

dossier.open("C:/Users/titib/Contacts/Desktop/Projet informatique/groupe/**gr**" + utilisateur + ".txt");
+4
source share
3 answers

This should work fine:

std::string FilePath = "C:/Users/titib/Contacts/Desktop/Projet informatique/groupe/" + std::to_string(gr)  + "/" + utilisateur + ".txt";
dossier.open(FilePath);
+2
source

You need to convert grto std::stringbefore you can add it to another line. Prior to C ++ 11, you can use std::ostringstream, for example:

#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, instead std::to_string():

dossier.open("C:/Users/titib/Contacts/Desktop/Projet informatique/groupe/" + std::to_string(gr) + "/" + utilisateur + ".txt");

Alternatively, in any version of C ++ you can use std::ostringstringto format the whole path:

std::ostringstream oss_path;
oss_path << "C:/Users/titib/Contacts/Desktop/Projet informatique/groupe/" << gr << "/" << utilisateur << ".txt";
dossier.open(oss_path.str());
+1

, . .

:

  • gr is now called groupe - the group is a string to avoid conversion.

I used filedirectory. Here is 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.

0
source

Source: https://habr.com/ru/post/1653196/


All Articles