C++中string与int的相互转换实现代码

2025-05-27 0 42

做ACM时,经常用到string和int的转换,下面的程序:

核心代码:

?

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

36

37

38

39

40

41

42

43
#include<iostream>

#include<string>

#include<sstream>

using namespace std;

int main()

{

/////////////////////////// string 转为 int

string str="1234";

int n;

istringstream iss;//istringstream从string读入,和cin一样仅仅重载了>>,可以把string转为int

iss.clear();//每次使用前先清空

iss.str(str);

iss>>n;//将输入流中的内容写入到int n,

cout<<n<<endl;

//////////////////////////////// int 转为 string

n=111;

ostringstream oss;//用于向string写入,和cout<<一样,仅仅重载了<<

oss<<n;

str=oss.str();

cout<<str<<endl;

///////////////////////////////// string 转为 int

str="22222";

sscanf(str.c_str(),"%d",&n); //scanf前面加s用于把str输入到n中

cout<<n<<endl;

/////////////////////////////// int 转为 string

int ss=1000;

char temp[64];

sprintf(temp,"%d",ss); //printf前面加s用于将ss按整数形式输出到数组temp中,不能直接给str.c_str();

str=temp;//再把数组temp赋值给str;

cout<<str<<endl;

return 0;

}

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 C++中string与int的相互转换实现代码 https://www.kuaiidc.com/73641.html

相关文章

发表评论
暂无评论