C语言atoi函数的用法

#include < stdlib.h >

int atoi(const char *nptr);

用法:将字符串里的数字字符转化为整形数。返回整形值。

注意:转化时跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时(‘/0’)才结束转换,并将结果返回。

例:

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

int main()
{
    char *ptr1 = "-12345.12";
    char *ptr2 = "+1234w34";
    char *ptr3 = "   456er12";
    char *ptr4 = "789 123";
    int a,b,c,d;

    a = atoi(ptr1);
    b = atoi(ptr2);
    c = atoi(ptr3);
    d = atoi(ptr4);

    printf("a = %d, b = %d, c = %d, d = %d/n", a,b,c,d);

    return 0;
}

输出结果:a = 12345, b = 1234, c = 456, d = 789

猜你喜欢

转载自blog.csdn.net/csdn_kou/article/details/81267625
今日推荐