string与int和char之间的类型转换问题

**string字符串转化为int**
①:
    #include<stdlib.h>
    string a;
    cin >> a;//1111
    int n1 = atoi(a.c_str());//n1=1111;

②:
    #include <sstream>
    stringstream stream;

    string result="10000";
    int n=0;
    stream<<result;
    stream>>n;//n等于10000
    // stream.clear(); //在进行多次转换前,必须清除stream


**intstring字符串**

①:
    int res=1111;
    string test = to_string(res);//将数字转化为string

②:
    #include <string>
    #include <sstream>
    #include <iostream> 

    int main()
    {
        std::stringstream stream;
        std::string result;
        int i = 1000;
        stream << i; //将int输入流
        stream >> result; //从stream中抽取前面插入的int值
        std::cout << result << std::endl; // print the string "1000"
    } 




**intchar数组**
①:
    //itoa貌似已经被遗弃,做法不安全,oj平台无法通过,vc,code不可以,vs可以
    #include<iostream>
    #include<string>
    #include<algorithm>
    #include<stdlib.h>
    using namespace std;
    int main()
    {
        char str[32];
        int num = 88;
        itoa(num, str, 10);//10为10进制
        cout << str;
    }
②:
    int n = 10000;
    char s[10];
    sprintf(s,"%d", n);// s中的内容为“10000”,,%d写错就会报错
    cout << s;
③:
    #include <sstream>
    #include <iostream> 
    int main()
    {
        std::stringstream stream;
        char result[8] ;
        stream << 8888; //向stream中插入8888
        stream >> result; //抽取stream中的值到result
        std::cout << result << std::endl; // 屏幕显示 "8888"
    } 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值