国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++ 整型與字符串的互轉(zhuǎn)方式

2020-01-26 13:21:43
字體:
供稿:網(wǎng)友

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)容了,希望能給大家一個(gè)參考,也希望大家多多支持武林網(wǎng)。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 临桂县| 两当县| 阿勒泰市| 郑州市| 容城县| 南皮县| 抚州市| 衡山县| 藁城市| 阳城县| 会理县| 集安市| 静宁县| 西宁市| 建水县| 甘谷县| 乐业县| 正阳县| 湖州市| 巴林右旗| 白山市| 五华县| 泰顺县| 台南县| 右玉县| 德化县| 天镇县| 庆安县| 剑川县| 丹凤县| 昂仁县| 乌海市| 宁阳县| 沈阳市| 无极县| 河池市| 饶河县| 贵定县| 德惠市| 富顺县| 清水河县|