C++ 整型與字符串的互轉(zhuǎn)方式
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.”;
以上這篇C++ 整型與字符串的互轉(zhuǎn)方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C++中的移動構(gòu)造函數(shù)及move語句示例詳解
這篇文章主要給大家介紹了關(guān)于C++中移動構(gòu)造函數(shù)及move語句的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用C++具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-10-10
c++類成員函數(shù)如何做函數(shù)參數(shù)
這篇文章主要介紹了c++類成員函數(shù)如何做函數(shù)參數(shù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11
深入了解C語言結(jié)構(gòu)化的程序設(shè)計
這篇文章主要介紹了C語言編程中程序的一些基本的編寫優(yōu)化技巧,文中涉及到了基礎(chǔ)的C程序內(nèi)存方面的知識,非常推薦!需要的朋友可以參考下2021-07-07
Qt自繪實(shí)現(xiàn)蘋果按鈕滑動效果的示例代碼
這篇文章主要介紹了Qt自繪實(shí)現(xiàn)蘋果按鈕滑動效果的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
vector與map的erase()函數(shù)詳細(xì)解析
vector和map都不能將it++寫在for循環(huán)中,而在循環(huán)體內(nèi)erase(it)2013-09-09

