C语言实现英文法定格式日期转换

本文介绍如何使用C语言将用户输入的日期(格式:月/日/年)转换为英文法定格式,例如将'12/31/2021'转换为'Dated this 31 day of December, 2021.'。

代码示例c#include <stdio.h>

void convertToLegalDate(char *date) { int month, day, year; char month_name[12][15] = { 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' };

sscanf(date, '%d/%d/%d', &month, &day, &year);

printf('Dated this %d day of %s, 20%d.

', day, month_name[month - 1], year);}

int main() { char date[11];

printf('请输入日期(格式:月/日/年):');    scanf('%s', date);

convertToLegalDate(date);

return 0;}

代码说明

  1. convertToLegalDate 函数: - 接收一个字符串参数 date,表示用户输入的日期。 - 使用 sscanf 函数将日期字符串解析为月份、日期和年份。 - 定义一个二维字符数组 month_name 存储英文月份名称,通过月份索引访问对应的名称。 - 使用 printf 函数将日期格式化为英文法定格式并输出。

  2. main 函数: - 定义一个字符数组 date 用于存储用户输入的日期。 - 提示用户输入日期。 - 调用 convertToLegalDate 函数进行日期转换。

注意

  • 程序假定用户输入的日期格式正确,没有进行输入验证和错误处理。- 可以根据实际需求对程序进行扩展和修改,例如添加输入验证、支持其他日期格式等。

总结

本文提供了使用C语言实现英文法定格式日期转换的代码示例和详细说明。希望对你有所帮助!

C语言实现英文法定格式日期转换

原文地址: https://www.cveoy.top/t/topic/cOWv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录