I am doing a Date
class which takes a string
as a parameter that is like :
11/13/2007 9/23/2008 9/23/2008
... and set it month, date and year objects, How can I use the substr()
function, or are there any other functions ?
I am doing a Date
class which takes a string
as a parameter that is like :
11/13/2007 9/23/2008 9/23/2008
... and set it month, date and year objects, How can I use the substr()
function, or are there any other functions ?
In your case, I would use the good old C(!) sscanf
function:
unsigned int year, month, day;
char c;
if(sscanf(input, "%u/%u/%u%c", &month, &day, &year, &c) == 3)
{
// check ranges of your date variables!
}
You seem to use American date format, so I set the parameters accordingly.
Wondering why I'm reading an additional character ? It catches additional data at the end of your date string to detect invalid formats (if data follows, result will be 4, otherwise, only 3 values are read, which will be returned). One drawback: before the three numbers, white space is ignored, so if you wanted to disallow, you would need additional checks (e. g. "%n %n%u"
and comparing, if the two corresponding values are equal).
See sscanf documentation (scanf for parameters).
(If your input is a ::std::string
instance, you need to use sscanf(input.c_str(), ...)
, of course.)
If you are using C++11 you can use <regex>
library:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string date = "1/1/1970";
std::regex dateRegex("(\\d\\d?)/(\\d\\d?)/(\\d{4})");
std::smatch match;
if (regex_match(date, match, dateRegex)) {
std::cout << match.str(1) << std::endl;
std::cout << match.str(2) << std::endl;
std::cout << match.str(3) << std::endl;
}
else {
// error
}
return 0;
}
This is maybe an overkill for your situation but remember that by using regular expression you are also doing some form of validation on your input. In above example, if you pass anything that doesn't have the form dd/dd/dddd where "d" is a digit you will enter the "error" block of code. Of course, 99/99/9999 will count as a valid input but you can also solve that case with more complicated regex.
Another option for parsing strings with delimiter is using getline function.