सी ++ फ्लोट / डबल और इसके विपरीत करने के लिए स्ट्रिंग

इस ट्यूटोरियल में, हम सीखेंगे कि स्ट्रिंग को फ्लोटिंग-पॉइंट नंबरों में कैसे बदलें और इसके विपरीत उदाहरणों की मदद से।

सी ++ स्ट्रिंग फ्लोट और डबल रूपांतरण के लिए

एक स्ट्रिंग को फ्लोटिंग-पॉइंट नंबर में बदलने का सबसे आसान तरीका इन C ++ 11 फ़ंक्शन का उपयोग करना है :

  • std :: stof () - में कनवर्ट stringकरेंfloat
  • std :: stod () - में कनवर्ट stringकरेंdouble
  • std :: stold () - में कनवर्ट 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; )

आउटपुट

 num_float = 123.457 num_double = 123.457

उदाहरण 2: C ++ चार ऐरे को दोगुना करना

हम फ़ंक्शन का उपयोग करके किसी 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; )

आउटपुट

 num_double = 123.457

सी ++ फ्लोट और स्ट्रिंग रूपांतरण के लिए डबल

हम में बदल सकते हैं floatऔर doubleकरने के लिए stringउपयोग करते हुए सी ++ 11 std::to_string() कार्य करते हैं। पुराने C ++ कंपाइलर के लिए, हम std::stringstreamऑब्जेक्ट का उपयोग कर सकते हैं ।

उदाहरण 3: फ्लोट और डबल टू स्ट्रिंग का उपयोग करना 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; )

आउटपुट

 स्ट्रिंग टू स्ट्रिंग = 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

अनुशंसित पढ़ना: C ++ स्ट्रिंग टू इंट।

दिलचस्प लेख...