C语言数字与字符串转换 atoi()函数、itoa()函数、sprintf()函数
2013-12-18 11:14
411 查看
在编程中经常需要用到数字与字符串的转换,下面就总结一下。
1.atoi()
C/C++标准库函数,用于字符串到整数的转换。
函数原型:int atoi (const char * str);
另外C/C++还提供的标准库函数有:
(1)long int atol ( const char * str );
(2)double atof (const char* str);
2.itoa()
不是C/C++标准库函数,用于整数到字符串的转换。
函数原型:
3.sprintf()
C/C++标准库函数,可以用于整数到字符串的转换。
sprintf:Write formatted data to string。
sprintf作用是将printf的输出结果保存在字符串数组中。
1.atoi()
C/C++标准库函数,用于字符串到整数的转换。
函数原型:int atoi (const char * str);
#include <stdio.h> #include <stdlib.h> int main () { char *numchars="1234"; int num=atoi(numchars); printf("%d\n",num); return 0; }
另外C/C++还提供的标准库函数有:
(1)long int atol ( const char * str );
(2)double atof (const char* str);
2.itoa()
不是C/C++标准库函数,用于整数到字符串的转换。
函数原型:
char
*itoa(
int
value,
char
*string,
int
radix);
#include <stdio.h> #include <stdlib.h> int main () { int num=1234; int radix=8; char res[20]; itoa(num,res,radix); printf("%d(10)=%s(%d)\n",num,res,radix); //输出:1234(10)=2322(8) return 0; }
3.sprintf()
C/C++标准库函数,可以用于整数到字符串的转换。
sprintf:Write formatted data to string。
sprintf作用是将printf的输出结果保存在字符串数组中。
#include <stdio.h> #include <stdlib.h> int main () { int num=1234; char res[20]; sprintf(res,"%0o",num); printf("%s\n",res); //8进制输出:2322 sprintf(res,"%0x",num); printf("%s\n",res); //16进制输出:4d2 return 0; }
相关文章推荐
- C语言数字与字符串转换 atoi()函数、itoa()函数、sprintf()函数
- C语言atoi()函数:将字符串转换成int(整数)和sprintf和memset
- C语言atoi()函数:将字符串转换成int(整数) 会自动把里面的非数字抛出 转换是数字的
- atoi() 函数与 itoa() 函数:字符串与数值之间的转换
- 编写一个函数,将一个数字字符串转换成该字符串对应的数字(包括正整数、负整数) 例如:“12“ 返回12 “-123“ 返回-123 函数原型:int my_atoi(char *str) {}
- 【c语言】编写一个函数,将一个数字字符串转换成这个字符串对应的数字(包括正浮点数、负浮点数)
- 不使用itoa或sprintf等系统函数完成整型向字符串的转换
- 【C语言】编写一个函数,将一个数字字符串转换成该字符串对应的数字(包括正整数、负整数)
- C语言 编写一个函数,将一个数字字符串转换成这个字符串对应的数字(包括正浮点数、负浮点数)
- C语言数字字符串转换为十六进制格式函数
- C语言atoi()函数:将字符串转换成int(整数)
- 【c语言】为下面的函数原型编写函数定义,这个字符串参数必须包含一个或者多个数字,函数应该把这些数字字符转换为整数并返回这个整数。
- C语言atoi()函数:将字符串转换成int(整数)
- 为函数原型编写函数定义:int my_atoi(char *str);(将一个数字字符串转换成该字符串对应的数字(包括正整数、负整数))
- 【C语言】为下面的函数原型编写函数定义: int ascii_to_integer(char *str); 这个字符串参数必须包含一个或者多个数字,函数应该把这些数字字符转换为整数并返回这个整数。
- 将数字n转换为字符串的函数itoa
- 数字转字符串(string)扩充说明及简单写数字和字符串转换代码(正式比赛的itoa和atoi用不了)
- 转:C语言中把数字转换为字符串-sprintf
- C语言实现atoi和itoa(字符串与数字之间的转化)
- stof()、atoi()、atol()、strtod()、strtol()、strtoul() 共6个可以将字符串转换为数字的函数