Ц ++ низ за плутање / удвостручавање и обрнуто

У овом упутству ћемо научити како претворити низ у бројеве са покретном зарезом и обрнуто уз помоћ примера.

Ц ++ низ за плутање и двоструку конверзију

Најлакши начин за претварање низа у број са покретном зарезом је коришћење ових функција Ц ++ 11 :

  • стд :: стоф () - претвори stringуfloat
  • стд :: стод () - претвори stringуdouble
  • стд :: столд () - претвори stringу long double.

Ове функције су дефинисане у stringзаглављу датотеке.

Пример 1: Ц ++ низ за плутање и удвостручавање

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

Оутпут

 нум_флоат = 123.457 нум_доубле = 123.457

Пример 2: Ц ++ цхар низ за удвостручавање

Помоћу функције можемо претворити charниз у .doublestd::atof()

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

Оутпут

 нум_доубле = 123.457

Ц ++ флоат и двострука конверзија у стринг

Можемо претворити floatи doubleу stringпомоћу функције Ц ++ 11 std::to_string() . За старије Ц ++ компајлере можемо користити std::stringstreamобјекте.

Пример 3: лебдење и удвостручавање у низ Коришћење то_стринг ()

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

Оутпут

 Флоат то Стринг = 123.456703 Доубле то Стринг = 123.456700

Пример 4: лебдење и удвостручавање у стринг помоћу стрингстреам-а

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

Оутпут

 Флоат то Стринг = 123.457 Доубле то Стринг = 123.457

Препоручено читање: Ц ++ стринг у инт.

Занимљиви Чланци...