C++: ostringstream 2

De Wiki de Calcul Québec
Aller à : Navigation, rechercher
Cette page est une traduction de la page C++ : ostringstream 2 et la traduction est complétée à 100 % et à jour.

Autres langues :anglais 100% • ‎français 100%

C++: manipulating strings using ostringstream

In C++, input/output streams are tools that deserve to be mastered. Their surprising functionality and their great extensibility are sometimes unrecognized. In fact, mastering streams is not a trivial task and those not in the know too often fall back to the C standard library (printf, scanf, fopen, etc.).

The standard function sprintf allows for writing formatted text to an array. However, its use comes with several annoying limitations, notably the fixed array length and the impossibility to write anything else than standard types (int, char*, double, etc.). One can be freed of these limitations using the ostringstream class, defined in the <sstream> header. This class allows for the manipulation of character strings like those in output streams. If, for example, you take the following code:

char buffer[100];
sprintf(buffer, "%s = %f", "PI", M_PI);

Using the ostringstream class, it becomes:

ostringstream oss;
oss << "PI = " << M_PI;

Of course, ostringstream offers a lot more features. You can benefit from stream manipulators like endl and setw(). You can also write class instances there (you only need to define the insertion operator <<). Finally. the length of the output string is unlimited.

See this more extensive example:

ostringstream oss;
oss << setw(10) << scientific << M_PI << endl
    << Sphere();
cout << oss.str();    // affichage de la chaîne à l'écran
Outils personnels
Espaces de noms

Ressources de Calcul Québec