Page principale | Pages associées

FAQ C++

Lecture d'un fichier ligne par ligne

// lecture_ligne.cpp #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream file( "source.cpp" ); string line; while( getline( file, line ) ) { cout << "Ligne lue [" << line << "]\n"; } }

Lecture de valeur séparée par des ';'

// lecture_valeur.cpp #include <iostream> #include <fstream> #include <sstream> #include <string> using namespace std; int main() { ifstream file( "data.txt" ); string line; while( getline( file, line ) ) { istringstream iss( line ); string valeur; while( getline( iss, valeur, ';' ) ) cout << '[' << valeur << ']'; cout << endl; } }

Transformation d'un nombre (entier, réel,... ) en chaîne

// transformation_nombre.cpp #include <iostream> #include <string> #include <sstream> using namespace std; template< typename T > std::string NumToStr( const T& t ) { ostringstream oss; oss << t; return oss.str(); } int main() { double valeur = 3.1415; cout << '[' << NumToStr( valeur ) << ']' << endl; }

Transformation d'une chaîne en un nombre (entier, réel,... )

// transformation_chaine.cpp #include <iostream> #include <string> #include <sstream> using namespace std; template< typename T > T StrToNum( const std::string& s ) { istringstream iss( s ); T t; iss >> t; return t; } int main() { string valeur = "3.1415"; cout << '[' << StrToNum<double>( valeur ) << ']' << endl; cout << '[' << StrToNum<int>( valeur ) << ']' << endl; }

Dernière modification : Sun Jul 4 20:19:14 2004