Comment parsingr une chaîne complexe avec C ++?

J’essaie de comprendre comment parsingr cette chaîne à l’aide de ” sstream ” et de C ++

Le format de celui-ci est le suivant: “ssortingng, int, int”.

Je dois pouvoir atsortingbuer la première partie de la chaîne qui contient une adresse IP à un std :: ssortingng.

Voici un exemple de cette chaîne:

 std::ssortingng("127.0.0.1,12,324"); 

J’aurais alors besoin d’obtenir

 ssortingng someSsortingng = "127.0.0.1"; int aNumber = 12; int bNumber = 324; 

Je mentionnerai à nouveau que je ne peux pas utiliser boost bibliothèque boost , juste sstream 🙂

Merci

Voici une fonction de tokenization utile. Il n’utilise pas de stream, mais peut facilement effectuer la tâche requirejse en séparant la chaîne par des virgules. Ensuite, vous pouvez faire ce que vous voulez avec le vecteur de jetons résultant.

 /// Ssortingng tokenizer. /// /// A simple tokenizer - extracts a vector of tokens from a /// ssortingng, delimited by any character in delims. /// vector tokenize(const ssortingng& str, const ssortingng& delims) { ssortingng::size_type start_index, end_index; vector ret; // Skip leading delimiters, to get to the first token start_index = str.find_first_not_of(delims); // While found a beginning of a new token // while (start_index != ssortingng::npos) { // Find the end of this token end_index = str.find_first_of(delims, start_index); // If this is the end of the ssortingng if (end_index == ssortingng::npos) end_index = str.length(); ret.push_back(str.substr(start_index, end_index - start_index)); // Find beginning of the next token start_index = str.find_first_not_of(delims, end_index); } return ret; } 

La bibliothèque C ++ Ssortingng Toolkit (Strtk) propose la solution suivante à votre problème:

 int main()
 {
    std :: ssortingng data ("127.0.0.1,12,324");
    ssortingng someSsortingng;
    int aNumber;
    int bNumber;
    strtk :: parse (data, ",", someSsortingng, aNumber, bNumber);
    retourne 0;
 }

Plus d’exemples peuvent être trouvés ici

Ce n’est pas compliqué mais vous pouvez utiliser std :: getline pour scinder la chaîne:

 std::ssortingng example("127.0.0.1,12,324"); std::ssortingng temp; std::vector tokens; std::issortingngstream buffer(example); while (std::getline(buffer, temp, ',')) { tokens.push_back(temp); } 

Ensuite, vous pouvez extraire les informations nécessaires de chacune des chaînes séparées.

Vous pouvez faire quelque chose comme ça aussi, je crois (Totalement, je vous prie de m’excuser si j’ai commis des erreurs là-dedans) …

 ssortingngstream mySsortingngStream( "127.0.0.1,12,324" ); int ipa, ipb, ipc, ipd; char ch; int aNumber; int bNumber; mySsortingngStream >> ipa >> ch >> ipb >> ch >> ipc >> ch >> ipd >> ch >> aNumber >> ch >> bNumber; ssortingngstream someSsortingngStream; someSsortingngStream << ipa << "." << ipb << "." << ipc << "." << ipd; string someString( someStringStream.str() );