如何解析和验证C ++中的std :: string中的日期? [英] How to parse and validate a date in std::string in C++?

查看:115
本文介绍了如何解析和验证C ++中的std :: string中的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个项目,我必须读一个日期,以确保它是一个有效的日期。例如,2月29日只是闰年的有效日期,或6月31日不是有效的日期,因此计算机将根据输入输出该信息。我的问题是,我不知道如何解析字符串,以便用户可以输入05/11/1996作为日期(例如),然后把它,并将其放入单独的整数。我正在想用一个while循环和字符串流做一些事情,但我有点卡住。

I'm working on a project where I have to read a date to make sure that it's a valid date. For example, February 29th is only a valid date on leap years, or June 31st is not a valid date, so the computer would output that information based on the input. My issue is that I can't figure out how to parse the string so that the user can enter "05/11/1996" as a date (for example) and then take that and put it into seperate integers. I was thinking about trying to do something with a while loop and string stream, but I'm a little stuck. If someone could help me with this, I would really appreciate it.

推荐答案

如果格式像你的例子中一样,你可以取出整数如下:

If the format is like in your example, you could take out the integer like this:

int day, month, year;
sscanf(buffer, "%2d/%2d/%4d",
    &month,
    &day,
    &year);

当然在缓冲区中你有日期(05/11/1996)

where of course in buffer you have the date ("05/11/1996" )

这篇关于如何解析和验证C ++中的std :: string中的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆