十年網(wǎng)站開發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
這篇文章主要介紹“C++整型與字符串的互轉(zhuǎn)方法”,在日常操作中,相信很多人在C++整型與字符串的互轉(zhuǎn)方法問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”C++整型與字符串的互轉(zhuǎn)方法”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
flyfish
字符串轉(zhuǎn)整型
C的方法 cstr是char*或者const char*類型的字符串
int num = atoi(str); int num = strtol(cstr, NULL, 10);
//10 表示進(jìn)制
C++11的方法
void test1(){ std::string str1 = "1";std::string str2 = "1.5";std::string str3 = "1 with words";int myint1 = std::stoi(str1);int myint2 = std::stoi(str2);int myint3 = std::stoi(str3);std::cout << "std::stoi(\"" << str1 << "\") is " << myint1 << '\n';std::cout << "std::stoi(\"" << str2 << "\") is " << myint2 << '\n';std::cout << "std::stoi(\"" << str3 << "\") is " << myint3 << '\n';}
結(jié)果輸出
std::stoi(“1”) is 1 std::stoi(“1.5”) is 1 std::stoi(“1 with words”) is 1
//源碼參考cplusplus.com
void test2(){ std::string str_dec = "2001, A Space Odyssey"; std::string str_hex = "40c3"; std::string str_bin = "-10010110001"; std::string str_auto = "0x7f"; std::string::size_type sz; // alias of size_t int i_dec = std::stoi (str_dec,&sz); int i_hex = std::stoi (str_hex,nullptr,16); int i_bin = std::stoi (str_bin,nullptr,2); int i_auto = std::stoi (str_auto,nullptr,0); std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n"; std::cout << str_hex << ": " << i_hex << '\n'; std::cout << str_bin << ": " << i_bin << '\n'; std::cout << str_auto << ": " << i_auto << '\n'; return 0;}
輸出
2001, A Space Odyssey: 2001 and [, A Space Odyssey] 40c3: 16579 -10010110001: -1201 0x7f: 127
其他類型 類似
無符號整型
stoul
浮點(diǎn)型
stof
數(shù)值轉(zhuǎn)字符串
std::string s; s = std::to_string(1) + ” is int, “;
其他數(shù)值類型 類似
s = std::to_string(3.14f) + ” is float.”;
到此,關(guān)于“C++整型與字符串的互轉(zhuǎn)方法”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!