C++ 整型與字符串的互轉方式
flyfish
字符串轉整型
C的方法 cstr是char*或者const char*類型的字符串
int num = atoi(str);
int num = strtol(cstr, NULL, 10);
//10 表示進制
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'; }
結果輸出
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
浮點型
stof
數(shù)值轉字符串
std::string s;
s = std::to_string(1) + ” is int, “;
其他數(shù)值類型 類似
s = std::to_string(3.14f) + ” is float.”;
以上這篇C++ 整型與字符串的互轉方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
字符串拷貝函數(shù)memcpy和strncpy以及snprintf 的性能比較
以下是對字符串拷貝函數(shù)memcpy和strncpy以及snprintf它們之間的性能進行了比較,需要的朋友可以過來參考下2013-07-07C++實現(xiàn)LeetCode(124.求二叉樹的最大路徑和)
這篇文章主要介紹了C++實現(xiàn)LeetCode(124.求二叉樹的最大路徑和),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-07-07舉例剖析C++中引用的本質及引用作函數(shù)參數(shù)的使用
這篇文章主要介紹了C++中引用的本質及引用作函數(shù)參數(shù)的使用,講解了函數(shù)返回值是引用的情況等一些難點,需要的朋友可以參考下2016-03-03