做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;
}
|
相关文章
猜你喜欢
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-29 53
-
2025-05-29 100
-
2025-05-27 83
-
2025-05-26 22
-
在CentOS7系统上编译安装MySQL 5.7.13步骤详解
2025-05-25 96
热门评论

