字符串转换为整数(类型为int)

使用atoi() 函数用来将字符串转换成整数(类型为int)

头文件:#include<stdlib.h>

函数声明: 

 int atoi(const char *str)

参数:

    str为要转换为整数的字符串

返回值:

    该函数返回转换后的长整数,如果没有执行有效的转换,则返回0

函数说明:

    函数会扫描str字符串,如果第一个非空格字符既不是数字也不是正负号,则返回0;否则,开始进行类型转换,直到遇到非数字或字符串结束('\0')时停止转换,返回结果

实例:

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

int main()
{
    char *str1 = "123abc";
    char *str2 = "abc123";
    int s1 = atoi(str1);
    int s2 = atoi(str2);
    printf("字符串 %s 转换为整数值 = %d\n", str1, s1);
    printf("字符串 %s 转换为整数值 = %d\n", str2, s2);
    return 0;
}

执行结果:

猜你喜欢

转载自blog.csdn.net/L5494326/article/details/121750785
今日推荐