0
点赞
收藏
分享

微信扫一扫

C++中字符串和数字相互转换的常用函数

非衣所思 2022-01-26 阅读 143


1.字符串转数字函数

字符串转数字是编程中常见的需求,自己手写这个需求倒不是很难,但是如果有直接可以调用的库则是十分便捷的。为此,C++标准库提供了一系列的字符串转数字 的函数。常用的如下:

1.1​​stoi()​​函数


  • 这里的​​stoi​​​意思即是​​string to int​​​,简写下来就是​​stoi()​​函数。
  • 简单示例

#include<cstdio>
#include<cstring>
#include<iostream>

using namespace std;

int main(){
string a = "2";
int a1 = stoi(a);
cout << "a1 = "<< a1 <<"\n";
}
  • 执行结果
    C++中字符串和数字相互转换的常用函数_#include

1.2 ​​stod()​​函数


  • ​string to double​
  • 简单示例

#include<cstdio>
#include<cstring>
#include<iostream>

using namespace std;

int main(){
string b = "2.3";
double b1 = stod(b);
cout << "b1 = "<< b1 << "\n";
}
  • 执行结果
    C++中字符串和数字相互转换的常用函数_字符串转数字_02


举报

相关推荐

0 条评论