string转换为数值型,stoi( )的用法等
从string转换到数值型
stoi string to integer
将字符串转换为整数,解析str,将其内容解释为指定基的整数值,并将其作为int值返回。
若idx非空,函数将idx的值设置为str中数字后的第一个字符的位置。若该参数为空nullptr,则不使用。
base默认为10。base(进制)决定了哪些字符是有效,的以及它们的翻译。若base设为0,所使用的基数由序列中的格式决定。
//函数声明
int stoi (const string& str, size_t* idx = 0, int base = 10);
int stoi (const wstring& str, size_t* idx = 0, int base = 10);
//
size_t sz;
string a = " 101dsaada,ff";
string c = " 1010";
string d = "0xff";
cout << stoi(a, &sz) << endl; //101
cout << a[sz] << endl; //d &sz指向了d(第一个非数字字符)
cout << stoi(c) << endl; //1010
cout << stoi(c, nullptr, 8) << endl; //520
cout << stoi(c, nullptr, 0) << endl; //1010
cout << stoi(d) << endl; //0
cout << stoi(d, nullptr, 0) << endl; //255
cout << stoi(d, nullptr, 2) << endl; //0
string b = "s10";
string e = "100000000000000000000";
cout << stoi(b) << endl; //异常:字符串不合法
cout << stoi(e) << endl; //异常:转换后超出int范围
stol string to long
stoul string to unsigned long
stoll string to long long
stoull string to unsigned long long
以上和转换为int的情况类似,只是数字大小范围有变化。注意无符号数的合法范围为|0 ~ 2^n -1|,n是位数,在这个范围内的负数不会抛出异常,而是输出为:该负数加上模值2^n。
stod string to double
//函数声明
double stod (const string& str, size_t* idx = 0);
double stod (const wstring& str, size_t* idx = 0);
//
size_t sz;
double e = 10.;
string a = " 10001.e";
string b = "12.5e2a5";
cout << stod(a, &sz) << endl; //10001
cout << a[sz] << endl; //e &sz指向e
cout << stod(b, &sz) << endl; //1250
cout << b[sz] << endl; //a &sz指向a
stof string to double
stold string to long double
和stod同理。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程