সম্ভাব্য বিকল্পগুলি নীচে বর্ণিত:
1. প্রথম বিকল্প: sscanf ()
#include <cstdio>
#include <string>
int i;
float f;
double d;
std::string str;
// string -> integer
if(sscanf(str.c_str(), "%d", &i) != 1)
// error management
// string -> float
if(sscanf(str.c_str(), "%f", &f) != 1)
// error management
// string -> double
if(sscanf(str.c_str(), "%lf", &d) != 1)
// error management
এটি একটি ত্রুটি (সিপিচেক দ্বারাও প্রদর্শিত) কারণ "ক্ষেত্রের প্রস্থের সীমা ছাড়াই স্ক্যানফ libc এর কয়েকটি সংস্করণে বিশাল ইনপুট ডেটা দিয়ে ক্র্যাশ করতে পারে" (দেখুন এখানে এবং এখানে ))
২. দ্বিতীয় বিকল্প: স্ট্যান্ড :: স্টো * ()
#include <iostream>
#include <string>
int i;
float f;
double d;
std::string str;
try {
// string -> integer
int i = std::stoi(str);
// string -> float
float f = std::stof(str);
// string -> double
double d = std::stod(str);
} catch (...) {
// error management
}
এই সমাধানটি সংক্ষিপ্ত এবং মার্জিত, তবে এটি কেবল সি ++ 11 অনুবর্তী কম্পাইলারগুলিতে উপলভ্য।
3. তৃতীয় বিকল্প: sstreams
#include <string>
#include <sstream>
int i;
float f;
double d;
std::string str;
// string -> integer
std::istringstream ( str ) >> i;
// string -> float
std::istringstream ( str ) >> f;
// string -> double
std::istringstream ( str ) >> d;
// error management ??
তবে এই সমাধানটি দিয়ে খারাপ ইনপুট ( এখানে দেখুন ) এর মধ্যে পার্থক্য করা শক্ত ।
৪. চতুর্থ বিকল্প: বুস্টের লেজিক্যাল_কাস্ট
#include <boost/lexical_cast.hpp>
#include <string>
std::string str;
try {
int i = boost::lexical_cast<int>( str.c_str());
float f = boost::lexical_cast<int>( str.c_str());
double d = boost::lexical_cast<int>( str.c_str());
} catch( boost::bad_lexical_cast const& ) {
// Error management
}
তবে এটি কেবল একটি মোড়ক sstream
, এবং ডকুমেন্টেশনগুলি sstream
আরও ভাল ত্রুটি পরিচালনার জন্য ব্যবহার করার পরামর্শ দেয় ( এখানে দেখুন )।
5. পঞ্চম বিকল্প: স্ট্রটো * ()
ত্রুটি পরিচালনার কারণে এই সমাধানটি খুব দীর্ঘ। যেহেতু কোনও ক্রিয়াকলাপ কোনও সরল ইন্টি ফেরায় না তাই পূর্ণসংখ্যার ক্ষেত্রে একটি রূপান্তর প্রয়োজন ( কীভাবে এই রূপান্তরটি অর্জন করা যায় তা এখানে দেখুন )।
Six. ষষ্ঠ বিকল্প: Qt
#include <QString>
#include <string>
bool ok;
std::string;
int i = QString::fromStdString(str).toInt(&ok);
if (!ok)
// Error management
float f = QString::fromStdString(str).toFloat(&ok);
if (!ok)
// Error management
double d = QString::fromStdString(str).toDouble(&ok);
if (!ok)
// Error management
উপসংহার
সংক্ষেপে, সর্বোত্তম সমাধান হ'ল সি ++ 11 std::stoi()
বা দ্বিতীয় বিকল্প হিসাবে কিউটি লাইব্রেরি ব্যবহার। অন্যান্য সমস্ত সমাধান নিরুৎসাহিত বা বগী।
atoi()
?