Chaîne C ++ à float / double et vice-versa

Dans ce tutoriel, nous allons apprendre à convertir une chaîne en nombres à virgule flottante et vice versa à l'aide d'exemples.

Chaîne C ++ en float et double conversion

Le moyen le plus simple de convertir une chaîne en nombre à virgule flottante consiste à utiliser ces fonctions C ++ 11 :

  • std :: stof () - convertir stringenfloat
  • std :: stod () - convertir stringendouble
  • std :: stold () - convertir stringen long double.

Ces fonctions sont définies dans le stringfichier d' en- tête.

Exemple 1: chaîne C ++ à flotter et doubler

 #include #include int main() ( std::string str = "123.4567"; // convert string to float float num_float = std::stof(str); // convert string to double double num_double = std::stod(str); std:: cout<< "num_float = " << num_float << std::endl; std:: cout<< "num_double = " << num_double << std::endl; return 0; )

Production

 num_float = 123,457 num_double = 123,457

Exemple 2: Tableau de caractères C ++ à doubler

Nous pouvons convertir un chartableau en doubleen utilisant la std::atof()fonction.

 #include // cstdlib is needed for atoi() #include int main() ( // declaring and initializing character array char str() = "123.4567"; double num_double = std::atof(str); std::cout << "num_double = " << num_double << std::endl; return 0; )

Production

 num_double = 123,457

Conversion flottante C ++ et double en chaîne

Nous pouvons convertir floatet doubleà l' stringaide du C ++ 11 std::to_string() fonction. Pour les anciens compilateurs C ++, nous pouvons utiliser des std::stringstreamobjets.

Exemple 3: float et double to string Utilisation de to_string ()

 #include #include int main() ( float num_float = 123.4567F; double num_double = 123.4567; std::string str1 = std::to_string(num_float); std::string str2 = std::to_string(num_double); std::cout << "Float to String = " << str1 << std::endl; std::cout << "Double to String = " << str2 << std::endl; return 0; )

Production

 Flottant en chaîne = 123,456703 Double en chaîne = 123,456700

Exemple 4: float et double en chaîne en utilisant stringstream

 #include #include #include // for using stringstream int main() ( float num_float = 123.4567F; double num_double = 123.4567; // creating stringstream objects std::stringstream ss1; std::stringstream ss2; // assigning the value of num_float to ss1 ss1 << num_float; // assigning the value of num_float to ss2 ss2 << num_double; // initializing two string variables with the values of ss1 and ss2 // and converting it to string format with str() function std::string str1 = ss1.str(); std::string str2 = ss2.str(); std::cout << "Float to String = " << str1 << std::endl; std::cout << "Double to String = " << str2 << std::endl; return 0; )

Production

 Flottant en chaîne = 123,457 Double en chaîne = 123,457

Lecture recommandée: chaîne C ++ en int.

Articles intéressants...