IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

SL & STL C++ Discussion :

Convertir un string en char**


Sujet :

SL & STL C++

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Profil pro
    Inscrit en
    Octobre 2008
    Messages
    31
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2008
    Messages : 31
    Par défaut Convertir un string en char**
    Bonjour,
    j'ai un string p qui contient des mots séparés par des espaces. Je voudrais créer un tableau de pointeurs char** qui contienne les mots de mon string. J'ai essayé le bout de code suivant qui ne fonctionne pas :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    Proj::Proj(string p)
    {
    istringstream stream1;
    stream1.str(p);
    string arg;
    int nb_arg=0;
     
    while (stream1 >> arg )
    {
       tab_arg[nb_arg]=(const_cast<char*>(arg.c_str()));
      nb_arg++;
    }
    }

    D'autre part, nb_arg et tab_arg sont des attributs de ma classe Proj,et je suis obligé, à la fin du constructeur de mettre Proj::nb_arg=nb_arg ; sinon, nb_arg contient n'importe quoi (un entier monstrueux) quelqu'un sait pourquoi ?
    Merci d'avance

    Tonio

  2. #2
    Membre averti
    Profil pro
    Inscrit en
    Octobre 2008
    Messages
    31
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2008
    Messages : 31
    Par défaut
    Au fait, pour justifier la conversion de string en char**, je dois préciser que j'utilise une fonction issue d'une bibliothèque C qui prend un char** en argument.

  3. #3
    screetch
    Invité(e)
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    #include <string>
    #include <vector>
    #include <malloc.h>
    using namespace std;
     
    vector<string> tokenize(const string& str,const string& delimiters)
    {
    	vector<string> tokens;
     
    	// skip delimiters at beginning.
        	string::size_type lastPos = str.find_first_not_of(delimiters, 0);
     
    	// find first "non-delimiter".
        	string::size_type pos = str.find_first_of(delimiters, lastPos);
     
        	while (string::npos != pos || string::npos != lastPos)
        	{
            	// found a token, add it to the vector.
            	tokens.push_back(str.substr(lastPos, pos - lastPos));
     
            	// skip delimiters.  Note the "not_of"
            	lastPos = str.find_first_not_of(delimiters, pos);
     
            	// find next "non-delimiter"
            	pos = str.find_first_of(delimiters, lastPos);
        	}
     
    	return tokens;
    }
     
    Proj::proj(string p)
    {
      vector<string> tokens = tokenize(p);
      size_t nb_args = tokens.size();
      char **args = malloc(sizeof(char*)*(nb_args+1));
      for(size_t i = 0; i < nb_args; ++i)
        args[i] = tokens[i].c_str();
      args[nb_args] = 0; //si il faut terminer le char** par un pointeur nul, ce qui se fait souvent
      doStuff(nb_args, args);
      free(args);
    }

  4. #4
    Membre averti
    Profil pro
    Inscrit en
    Octobre 2008
    Messages
    31
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2008
    Messages : 31
    Par défaut
    Merci beaucoup, je ne suis pas loin du but, mais il m'a fallu caster le resultat de c_str pour l'affecter à args[i]
    J'ai encore un problème avec le malloc, le compilateur me sort : invalid conversion from void* to char** ?
    Merci
    Tonio

  5. #5
    Membre averti
    Profil pro
    Inscrit en
    Octobre 2008
    Messages
    31
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2008
    Messages : 31
    Par défaut ca marche
    super ca marche ! j'ai mis un reinterpret_cast devant mon malloc et c'est bon : ca donne ca (j'ai quand même utilisé ma méthode avec isstream) :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    #include <iostream>
    #include <sstream>
    #include <vector>
    #include <malloc.h>
    #include <string>
     
    Proj::Proj(string p)
    {
    vector<string> vect_arg;  // vecteur de string contenant les mots du string p
    istringstream stream1; // flux associé au string p
    stream1.str(p);  // définition de stream1
    string arg;
     
    while (stream1 >> arg )  // lecture du flux stream1
    {
      vect_arg.push_back(arg); // remplissage de vect_arg
     }
     
     nb_arg=vect_arg.size();  // calcul du nombre de mots
     char **args=reinterpret_cast<char**>(malloc(sizeof(char*)*(nb_arg+1))); // allocation mémoire du tableau char** amené à contenir les mots
     for (size_t i=0;i<nb_arg;++i)
       args[i]=const_cast<char*>(vect_arg[i].c_str()); // conversion des string de vect_arg en char* dans args
     
     for (size_t i=0;i<nb_arg;++i)
       printf("%s\n",args[i]);  // impression
     args[nb_arg]=0;  // termine le char**
     
    };
    Merci beaucoup

    Tonio

  6. #6
    screetch
    Invité(e)
    Par défaut
    ca ou mettre les char* en const char* a la place. Näoublie pas qu'a chaque malloc doit correspondre un free

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. convertir un string en char[] à 1 dimension
    Par tortuegenie dans le forum ASP.NET
    Réponses: 2
    Dernier message: 15/02/2008, 14h06
  2. Convertir une string en Char* unsafe?
    Par UnSofteuxAmateur dans le forum Windows Forms
    Réponses: 4
    Dernier message: 06/02/2008, 17h09
  3. Réponses: 2
    Dernier message: 25/10/2006, 18h09
  4. comment convertir un string^ en char*?
    Par chrono23 dans le forum C++/CLI
    Réponses: 2
    Dernier message: 10/10/2006, 15h49
  5. [debutant] Comment convertir un string en char
    Par jbidou88 dans le forum AWT/Swing
    Réponses: 7
    Dernier message: 04/05/2006, 12h58

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo