atoi函数的作用是把一个字符串换成一个整型数据,该函数包含于头文件#include
1.空字符返回数字0;
2.数字字符前有空白字符跳过;
3.数字字符前有+、-号,做整数类型的正负处理;
4.数字字符前有其他字符返回0;
简单举例:
#include
#include
int main() {
char arr1[] = ""; //输出0
char arr2[] = " 123"; //输出123
char arr3[] = " -123"; //输出-123
char arr4[] = " +123"; //输出123
char arr5[] = "abc123"; //输出0
char arr6[] = "abc123zb";//输出0
int a1 = atoi(arr1);
int a2 = atoi(arr2);
int a3 = atoi(arr3);
int a4 = atoi(arr4);
int a5 = atoi(arr5);
int a6 = atoi(arr6);
printf("%d\n%d\n%d\n%d\n%d\n%d",a1,a2,a3,a4,a5,a6);
return 0;
}
结果展示:
#include
#include
#include
#include
#include
int my_atoi(char* str) {
assert(str);//空指针
if (*str == '\0')
return 0;
while (*str == ' ') {//跳过空格
str++;
}
int a = 1,num=0;
if (*str == '+') {//判断正负
str++;
}
else if (*str == '-') {//判断正负
a = -1;
str++;
}
long long n = 0;
while (isdigit(*str)) {
num = *str - '0';
n = n * 10 + a * num;
if (n > INT_MAX || n < INT_MIN)
return 0;
str++;
}
if (*str == '\0') {
return (int)n;
}
return (int)n;
}
int main() {
char arr1[] = ""; //输出0
char arr2[] = " 123"; //输出123
char arr3[] = " -123"; //输出-123
char arr4[] = " +123"; //输出123
char arr5[] = "abc123"; //输出0
char arr6[] = "abc123zb";//输出0
printf("%d\n%d\n%d\n%d\n%d\n%d", my_atoi(arr1),my_atoi(arr2),my_atoi(arr3),my_atoi(arr4),my_atoi(arr5),my_atoi(arr6));
return 0;
}
结果展示:
itoa函数的作用是将一个整数转换成字符串。该函数包含于头文件#include
用法:itoa(整型数据,目标字符串,进制)
而在vs 中要使用— _itoa函数才行。
简单举例:
#include
#include
int main()
{
int n = 123;
char num1[20] = { 0 };
char num2[20] = { 0 };
char num3[20] = { 0 };
char num4[20] = { 0 };
_itoa(n, num1, 10);//将整型的n转为十进制的字符数字存储在num中为123
_itoa(n, num2, 2);//将整型的n转为二进制的字符数字存储在num中为1111011
_itoa(n, num3, 8);//将整型的n转为八进制的字符数字存储在num中为1111011
_itoa(n, num4, 16);//将整型的n转为十六进制的字符数字存储在num中为1111011
printf("%s\n%s\n%s\n%s", num1,num2,num3,num4);
return 0;
}
结果展示:
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
void my_itoa(int num, char* str, int radix){
char* left = str;
int flag = num;
if (num < 0) //考虑到负数的情况
num = -num;
while (num > 0)
{
*str++ = num % radix + '0';
num /= radix;
}
if (flag < 0)
{
*str++ = '-';
}
*str = '\0';
//此时是逆序存放的,需要翻转过来
char* right = str - 1;
while (left < right)
{
char tmp = *left;
*left = *right;
*right = tmp;
++left;
--right;
}
}
int main()
{
int n = 123;
char num1[20] = { 0 };
char num2[20] = { 0 };
char num3[20] = { 0 };
char num4[20] = { 0 };
my_itoa(n, num1, 10);//将整型的n转为十进制的字符数字存储在num中为123
my_itoa(n, num2, 2);//将整型的n转为二进制的字符数字存储在num中为1111011
my_itoa(n, num3, 8);//将整型的n转为八进制的字符数字存储在num中为173
my_itoa(n, num4, 16);//将整型的n转为十六进制的字符数字存储在num中为7p
printf("%s\n%s\n%s\n%s", num1,num2,num3,num4);
return 0;
}
结果展示: