日常编码过程中,字符串与数字进行相互转换是常见的需求,下面我们总结一下在
c++
中,字符串与数字
的转换都是如何来进行操作的。
1.
字符串转数字
c
语言风格
首先看看,在
c
语言的风格中,我们怎么做到把字符串转为数字。
void func1() {
string s1 = "123";
string s2 = "123.1";
int i = atoi(s1.c_str());
double d = atof(s2.c_str());
cout<<i<<endl;
cout<<d<<endl;
}
1
2
3
4
5
6
7
8
注意上述代码是在
namespace
为
std
的环境中运行。
atoi, atof
函数,均在
stdlib.h
中进行了声明,在头文件中,其声明的函数原型为
double atof(const char *);
int atoi(const char *);
long atol(const char *);
1
2
3
不难看出,上面这些方法的输入均为
const char *
,即字符串,得到的输出为转化以后的各种数值类型。
123
123.1
1
2
2.
字符串转数字
c++
风格
void func2() {
string s1 = "456";
string s2 = "456.2";
int i = stoi(s1);
long l = stol(s1);
float f = stof(s2);
double d = stod(s2);
cout<<i<<endl;
cout<<l<<endl;
cout<<f<<endl;
cout<<d<<endl;
}
1
2
3
4
5
6
7
8
9
10