C++中的日期验证和转换
Date Validation and Conversion in C++
我必须写2个函数。一个将日期作为字符串并检查其是否为 mm/dd/yy 格式;如果格式不正确,则应对其进行编辑以使其正确。另一个函数应将验证日期转换为"月 dd, 20yy"格式。
我很确定我可以处理第二个功能,但我在处理第一个功能时遇到了麻烦。我只是不知道如何检查它是否采用这种格式......有什么想法吗?
我以为这会起作用,但似乎没有...
更新的代码:
bool dateValidation(string shipDate)
{
string temp;
if(shipDate.length() == 8 )
{
if(shipDate[2] == '/' && shipDate[5] =='/')
{
int tempDay, tempMonth, tempYear;
//Gather month
temp = shipDate[0];
temp += shipDate[1];
//convert string to int
tempMonth = temp.atoi;
temp = "";
//Gather day
temp = shipDate[3];
temp += shipDate[4];
//convert string to int
tempDay = temp.atoi;
temp = "";
//Gather year
temp = shipDate[6];
temp += shipDate[7];
//convert string to int
tempYear = temp.atoi;
temp = "";
if(tempMonth > 0 && tempMonth <= 12)
{
if(tempMonth == 9 ||
tempMonth == 4 ||
tempMonth == 6 ||
tempMonth == 11 ||)
{
if(tempDay > 0 && tempDay <= 30)
{
if 30 days
}
}
else if(tempMonth == 2)
{
if(tempDay > 0 && tempDay <= 28)
{
if 28 days
}
}
else
{
if(tempDay > 0 && tempDay <= 31)
{
if 31 days
}
}
}
}
}
}
您需要检查 4 件事:
- 有8个字符吗?如果没有,那么甚至不要费心检查其他任何东西。它的格式不正确。
- 是第三和第五个字符"/"。如果没有,那么您仍然没有正确的格式。
- 检查每对的有效值。一个月的天数介于 1 到 1 之间最多31个月,不超过12个月,月份范围从01到 12.年份可以是任意 2 位数字的任意组合。
这应该处理格式,但如果要确保日期有效:
- 检查每个月的有效天数(1 月 31 日、2 月28-29...)并确实检查那些闰年。
这看起来很像我即将评分的项目......如果它是我即将评分的项目,您应该验证它是否符合公历标准。 1/1/2012 绝对有效,所以您可能想要做的,我希望您考虑的是创建一个 switch 语句来检查 1/12/2012 和 10/2/2012 等格式,因为这些格式是有效的。然后从中解析出月日和年。然后验证它们是否在公历的限制范围内。如果是我猜的类,您应该考虑将验证编写为与解析函数分开的函数。
所以先问一下日期是不是太长了,是不是太短了,如果不是哪个版本,再把 d m y 传递给验证函数。这种模块化将简化您的代码并减少指令。
类似的东西
布尔日期验证(字符串发货日期){ 字符串温度;
switch(shipDate.length())
{
case(10):
// do what your doing
verify(m,d,y);
break;
case(8):
//dealing with single digits
// verify 1 and 3 are '/' and the rest are numbers
verifiy(m,d,y);
break;
case(9):
//a little more heavy lifting here
// but its good thinking for a new programmer
verifiy(m,d,y);
break;
default:
//fail message
break;
}
相关文章:
- 防止主数据类型C++的隐式转换
- 模板参数替换失败,并且未完成隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- HEX值到wchar_t字符(UTF-8)的转换
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将 Qvector<uint8_t> 转换为 QString
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中使用nlohmann从类到json的转换
- 正在尝试了解输入验证循环
- 用于验证类型的动态强制转换
- 验证用户输入是否有效 [从 'char' 到 'char*' 的转换无效]
- 转换和验证字符串
- C++中的日期验证和转换
- 无法验证从 time_point 到 tm 和 tm 返回 time_point 的转换
- 卡住了!使用整数、字符到整数转换、ASCII 和 MIDI 进行验证
- c++阿拉伯到罗马数字转换器-输入验证循环
- 验证八进制到十进制的转换
- 华氏到摄氏转换器.验证int而不是char
- 将Xaml文本框转换为double,但如何验证用户输入是double,而不是windows 8应用程序的c++中的字符串