विषय पर बढ़ें

अंतिम अद्यतन:2026-10-12

C++ string को int में बदलना

निजी public account:

wechat

सबसे पहले solutions प्रस्तावित करते हैं:

  • atoi
  • strtol
  • stoi

इनमें क्या अंतर है? नीचे test करके तुलना करते हैं।

C भाषा शैली के functions

atoi और strtol की तुलना:

string str = "16s";
int a = atoi(str.c_str());
int b = strtol(str.c_str(), nullptr, 10);

आउटपुट:

atoi的结果为:16
strtol的结果为:16

ये दोनों functions string की शुरुआत से digits या plus/minus sign या decimal point ढूंढते हैं, और किसी invalid character पर पहुंचते ही रुक जाते हैं।

इसलिए ऊपर वाले s character पर पहुंचते ही आउटपुट बंद हो जाता है, पहले ही समाप्त हो जाता है, यानी जब आपकी string digits वाली नहीं है, या decimal point जैसे non-digit characters हैं, तो कोई exception नहीं आता! सीधे 0 आउटपुट हो जाता है।

उदाहरण के लिए:

string str = "asdsa";
int a = atoi(str.c_str());
int b = strtol(str.c_str(), nullptr, 10);

आउटपुट:

0
0

strtol, atoi की तुलना में कई base conversions को सपोर्ट करता है, जैसे base 8 आदि

उदाहरण के लिए:

int b = strtol(str.c_str(), nullptr, 8);

C++ शैली

C++ में int में बदलने के लिए stoi का उपयोग किया जा सकता है, इस function की पिछले दोनों की तुलना में सबसे बड़ी खासियत है: exceptions!

हम जानते हैं कि C++, C भाषा की तुलना में exceptions की सुविधा देता है, यही इस function की C++ में सबसे उल्लेखनीय क्षमता है।

उदाहरण के लिए:

string str1 = "asq,";
//    int c = stoi(str1);    // 报异常
string str2 = "12312";
int c = stoi(str2);     // ok
cout << c << endl;

exception इस प्रकार है:

terminate called after throwing an instance of 'std::invalid_argument'
what():  stoi

स्वयं परिभाषित

यानी खुद ही लिख लेते हैं, इस प्रकार:

int stringToInt(const string &s) {
    int v;
    stringstream ss;
    ss << s;
    ss >> v;
    return v;
}
int main() {
    int i = stringToInt("2.3");
    cout<<i<<endl;
}

संबंधित विषय

टिप्पणियाँ