C ++ streng for at flyde / fordoble og omvendt

I denne vejledning lærer vi, hvordan man konverterer streng til flydende tal og omvendt ved hjælp af eksempler.

C ++ streng til at flyde og dobbeltkonvertering

Den nemmeste måde at konvertere en streng til et flydende nummer er ved hjælp af disse C ++ 11- funktioner:

  • std :: stof () - konverter stringtilfloat
  • std :: stod () - konverter stringtildouble
  • std :: stold () - konverter stringtil long double.

Disse funktioner er defineret i stringheaderfilen.

Eksempel 1: C ++ streng til at flyde og fordoble

 #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; )

Produktion

 num_float = 123.457 num_double = 123.457

Eksempel 2: C ++ char Array for at fordoble

Vi kan konvertere et chararray til doubleved hjælp af std::atof()funktionen.

 #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; )

Produktion

 num_dobbelt = 123.457

C ++ float og dobbelt til strengkonvertering

Vi kan konvertere floatog doubletil stringat bruge C ++ 11 std::to_string() funktion. For de ældre C ++ - kompilatorer kan vi bruge std::stringstreamobjekter.

Eksempel 3: flyd og dobbelt til streng ved hjælp af 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; )

Produktion

 Flyd til streng = 123.456703 Dobbelt til streng = 123.456700

Eksempel 4: flyd og dobbelt til streng ved hjælp af 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; )

Produktion

 Flyd til streng = 123.457 Dobbelt til streng = 123.457

Anbefalet læsning: C ++ streng til int.

Interessante artikler...