C/C++ 关于字符串类型和整型的互相转化

string到int

使用函数stoi(),该函数定义在<string>头文件中。

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s = "0123";
    int a = stoi(s);
    cout << a;
    return 0;
}

输出: 123

int到string

使用函数to_string(),定义在<string>头文件中。

#include <iostream>
#include <string>
using namespace std;

int main()
{
    int a = 123;
    string s = to_string(a);
    cout << s;
    return 0;
}

输出:123

char数组到int

使用函数atoi(),定义在头文件<stdlib.h>中。
用法:参数为要转化的char数组,返回int类型数据。

#include <cstdio>
#include <cstdlib>

int main()
{
    char str[10] = "123";
    int a;
    a = atoi(str);
    printf("%d", a);
    return 0;
}

输出:123

int到char数组

使用函数itoa(),定义在头文件<stdlib.h>中。
用法:第一个参数是要转换的整型变量,第二个参数是目的char数组,第三个参数是转换的基数(即十进制,八进制等等)

#include <cstdio>
#include <cstdlib>

int main()
{
    int a = 123;
    char str[10];
    itoa(a, str, 10);
    printf("%s", str);
    return 0;
}

输出: 123

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值