У цьому підручнику ми дізнаємось, як перетворити рядок на числа з плаваючою крапкою і навпаки, за допомогою прикладів.
Рядок C ++ для плаваючого та подвійного перетворення
Найпростіший спосіб перетворити рядок у число з плаваючою комою - це за допомогою цих функцій C ++ 11 :
- std :: stof () - перетворити
string
наfloat
- std :: stod () - перетворити
string
наdouble
- std :: stold () - перетворити
string
наlong double
.
Ці функції визначені у string
файлі заголовка.
Приклад 1: Рядок C ++ для плаваючого та подвійного
#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; )
Вихідні дані
num_float = 123.457 num_double = 123.457
Приклад 2: C ++ char Array для подвоєння
Ми можемо перетворити char
масив на double
за допомогою std::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; )
Вихідні дані
num_double = 123.457
Перетворення C ++ з плаваючою та подвійною в рядки
Ми можемо перетворити float
і double
на string
використання функції C ++ 11 std::to_string()
. Для старих компіляторів C ++ ми можемо використовувати std::stringstream
об'єкти.
Приклад 3: float і double у рядок за допомогою 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; )
Вихідні дані
Float to String = 123.456703 Double to String = 123.456700
Приклад 4: float та double у рядок за допомогою 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; )
Вихідні дані
Float to String = 123.457 Double to String = 123.457
Рекомендуємо прочитати: рядок C ++ для int.