首页 > 其他 > 详细

字符串和数字的相互转换

时间:2021-05-08 00:11:27      阅读:17      评论:0      收藏:0      [点我收藏+]

注:

  1. 为了叙述的方便,以下数字均指整形,其它类型同样具有对应函数
  2. C语言的字符串是指字符数组,C++的字符串是指string,两者并不相同

C语言

字符串\(->\)数字

  • atoi(): 将字符串转换为整型值

int atoi(const char *nptr);

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char str[10];
    scanf("%s", str);

    int n;
    n = atoi(str);

    printf("%d\n", n);

    return 0;
}
  • sscanf(): 从字符串中读取
    该函数的作用类似正则表达式,可以格式化字符串
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char str[10];
    scanf("%s", str);

    int n;
    sscanf(str, "%d", &n);

    printf("%d", n);

    return 0;
}

数字\(->\)字符串

  • itoa():将整型值转换为字符串

char *itoa (int value, char *str, int base );
int value: 被转换的整数
char *string: 转换后储存的字符数组
int base: 转换进制数,如2,8,10,16 进制等,大小在2-36之间

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n;
    scanf("%d", &n);

    char str[10];
    itoa(n, str, 10);

    printf("%s\n", str);

    return 0;
}
  • sprintf():将数字写入字符串中
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n;
    scanf("%d", &n);

    char str[10];
    sprintf(str, "%d", n);

    printf("%s", str);
    return 0;
}

C++

字符串\(->\)数字

数字\(->\)字符串

字符串和数字的相互转换

原文:https://www.cnblogs.com/G-H-Y/p/14742663.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!