一、string转化为数字
1.使用stoi
stoll(string to long long)
stoul(string to unsigned long)
stoull(string to unsigned long long)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
using
namespace
std
;
int
main
(
)
{
string
str
=
"123"
;
int
a
=
stoi
(
str
)
;
cout
<<
a
;
str
=
"123.44"
;
double
b
=
stod
(
str
)
;
cout
<<
b
;
return
0
;
}
/*
stoi如果是非法输入:
1.会自动截取最前面的数字,直到遇到不是数字为止
(所以说如果是浮点型,会截取前面的整数部分)
2.如果最前面不是数字,会运行时发生错误
*/
/*
stod如果是非法输入:
1.会自动截取最前面的浮点数,直到遇到不满足浮点数为止
2.如果最前面不是数字或者小数点,会运行时发生错误
3.如果最前面是小数点,会自动转化后在前面补0
*/
/*
相应的还有:
stof(string to float)
stold(string to long double)
stol(string to long)
stoll(string to long long)
stoul(string to unsigned long)
stoull(string to unsigned long long)
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <sstream>
using
namespace
std
;
int
main
(
)
{
string
str
=
"1234"
;
stringstream
stream
;
stream
<<
str
;
int
a
;
stream
>>
a
;
cout
<<
a
;
return
0
;
}
/*
如果转int是非法输入:
1.会自动截取最前面的数字,直到遇到不是数字为止
(所以说如果是浮点型,会截取前面的整数部分)
2.如果最前面不是数字,会转化为整数0
*/
/*
如果转double是非法输入:
1.会自动截取最前面的浮点数,直到遇到不满足浮点数条件为止
2.如果最前面不是数字或者小数点,会转化为整数0
3.如果最前面是小数点,会转化为浮点数后在前面自动补0
*/
/*
其他数字类型也可以转化
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cstdio>
using
namespace
std
;
int
main
(
)
{
char
c
[
50
]
=
"123"
;
int
a
;
sscanf
(
c
,
"%d"
,
&
a
)
;
// 不要忘记 “&”
int
b
=
567
;
sprintf
(
c
,
"%d"
,
b
)
;
cout
<<
a
<<
endl
<<
c
;
return
0
;
}
/*
sscanf将字符数组转换为数字,输入到数字变量中
sprintf将数字转换为字符数组,输出到字符数组变量中
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cstdio>
using
namespace
std
;
int
main
(
)
{
char
c
[
50
]
=
"123"
;
int
a
;
sscanf
(
c
,
"%d"
,
&
a
)
;
// 不要忘记 “&”
int
b
=
567
;
sprintf
(
c
,
"%d"
,
b
)
;
cout
<<
a
<<
endl
<<
c
;
return
0
;
}
/*
sscanf将字符数组转换为数字,输入到数字变量中
sprintf将数字转换为字符数组,输出到字符数组变量中
*/