在 C 语言 中我们要将一个 字符串 转成 整型 ,我们可以使用 atoi 函数。
int atoi(const char *str);
参数 | 描述 |
---|---|
str | 要转换为整数的字符串。 |
该函数返回转换后的长整数,如果没有执行有效的转换,则返回零。
使用 atoi 函数,需要引入 stdlib.h 头文件。
使用 atoi() 函数,实现将字符串转整型
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("嗨客网(www.haicoder.net)\n\n");
char str[] = "98765";
int ret;
ret = atoi(str);
printf("Atoi Num = %d\n", ret);
return 0;
}
程序运行后,控制台输出如下:
我们首先定义了一个 字符数组 str,里面存放的整数,接着,我们使用了 atoi 函数,实现了将字符数组 str 转成了 int 类型,并赋值给 ret。
最后,我们使用了 printf 打印出了转换后的整数,我们可以发现,我们成功的使用了 atoi 函数将字符串转成了 int 类型。
使用 atoi() 函数,实现将字符串转int
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("嗨客网(www.haicoder.net)\n\n");
char str[] = "Hello,HaiCoder";
int ret;
ret = atoi(str);
printf("Atoi Num = %d\n", ret);
return 0;
}
程序运行后,控制台输出如下:
这次,我们定义的字符数组里面存放的全部是字符串,我们再次使用 atoi 函数将其转成 int 类型时,转换失败,返回了 0。
在 C 语言中我们要将一个字符串转成整型 ,我们可以使用 atoi 函数。