温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-30 08:23:13 来源:脚本之家 阅读:135 作者:mdxy-dxy 栏目:编程语言

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

核心代码:

#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;
}

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI