每天认识一个函数(5)

一、atoi()函数

作用:把字符串转换为整数(类型为 int 型)。

1.头文件:

                 #include <stdlib.h>

2.格式:

                int atoi(const char *str)

3.返回值:

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

4.参数解析:

        str→ 要转换为整数的字符串。
以上来源:int atoi(const char *str) - C语言在线手册 (dba.cn)

示例一:输出当前日期

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{

	int  Year, Month, Day;
	const char *pMonth[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
	const char Date[12] = __DATE__;
    //__DATE__ :表示当前日期的字符串,格式为month/day/year(月/日/年).
	printf("Date : %s\n",Date);
	int i;
	for(i = 0; i < 12; i++)
    {
        if(memcmp(Date, pMonth[i], 3) == 0)
        {
            Month = i + 1;
            i = 12;
        }
    }
	Year = (int)atoi(Date + 9); 
	Day = (int)atoi(Date + 4);

	printf("%d年%02d月%d日",Year, Month, Day);

    Year = (int)atoi(Date + 7);
	printf("%d年%02d月%d日",Year, Month, Day);

	return 0;

}

输出:

Date : Jan 26 2024
24年01月26日
2024年01月26日



示例二:

#include <stdio.h>
#include <stdlib.h>
int main() {
    const char *str1 = "12345678";
    const char *str2 = "12345678a"; 
    const char *str3 = "a12345678"; 
    const char *str4 = "-123.45678a";
	const char *str5 = "-a123.45678";
    int value1 = atoi(str1);
    int value2 = atoi(str2);
    int value3 = atoi(str3); 
    int value4 = atoi(str4); 
    int value5 = atoi(str5); 
    printf("str1 = %d\n", value1);
    printf("str2 = %d\n", value2);
    printf("str3 = %d\n", value3); // 未定义的结果,通常为0
    printf("str4 = %d\n", value4); 
	printf("str5 = %d\n", value5); // 未定义的结果,通常为0
    return 0;
}

 输出:

str1 = 12345678
str2 = 12345678
str3 = 0
str4 = -123
str5 = 0

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值