Chinaunix首页 | 论坛 | 博客
  • 博客访问: 428920
  • 博文数量: 127
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 810
  • 用 户 组: 普通用户
  • 注册时间: 2013-07-02 20:51
文章分类

全部博文(127)

文章存档

2018年(6)

2015年(18)

2014年(33)

2013年(70)

分类: C/C++

2013-12-31 11:31:14

1,字符串转整型(一)
#include
int atoi(const char *nptr);
字符串转化为整型
long atol(const char *nptr);
字符串转化为长整型
long long atoll(const char *nptr);
long long atoq(const char *nptr);
字符串转化为long long 类型
英文手册很简单,直接上
说明:The atoi() function converts the initial portion of the string pointed to by nptr to int.  The behavior is the same as strtol(nptr, (char **) NULL, 10); except that atoi() does not detect errors. The  atol() and atoll() functions behave the same as atoi(), except that they convert the initial portion of the string to their return type of long or long long.  atoq() is an obsolete name for atoll().

2,字符串转整型(二)
#include
long int strtol(const char *nptr, char **endptr, int base);
字符串转长整型,base参数为进制,如转化为10进制,则base应该为10
long long int strtoll(const char *nptr, char **endptr, int base);
字符串转化为long long int
说明:详细说明请参考man手册。

3,字符串转浮点数
#include
double strtod(const char *nptr, char **endptr);
字符串转 双精度浮点数 double 类型
float strtof(const char *nptr, char **endptr);
字符串转 单精度浮点数 float 类型
long double strtold(const char *nptr, char **endptr);
字符串转 long double 类型

有了以上库函数,可以很方便的把字符串转化为数值型,真系灰常的方便啊,有木有?

示例代码:
  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. int main(){
  4.     char *str_int="892";
  5.     int int_val=atoi(str_int);
  6.     printf("字符串转整型:%d\n",int_val);
  7.     long long_val=atol(str_int);
  8.     printf("字符串转长整型:%ld\n",long_val);
  9.     char *str_float="238.23";
  10.     char *endptr;
  11.     float float_val=strtof(str_float,&endptr);
  12.     printf("字符串转单精度浮点型:%f\n",float_val);
  13.     double double_val=strtod(str_float,&endptr);
  14.     printf("字符串转双精度浮点型:%f\n",double_val);
  15.     char *str_long="9839282";
  16.     int base=10;
  17.     long long_v=strtol(str_long,&endptr,base);
  18.     printf("strtol : %ld\n",long_v);
  19.     return 0;
  20. }
代码输出:
  1. 字符串转整型:892
  2. 字符串转长整型:892
  3. 字符串转单精度浮点型:238.229996
  4. 字符串转双精度浮点型:238.230000
  5. strtol : 9839282

说明:以上各函数的man手册都有详尽的解释,详情请查阅man手册。

阅读(1243) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~