Date as a string to date float

How can i do this

the date format is 12/15/2015

Hello nickhere,

This is something simple you could try:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <sstream>

int main()
{
	std::string date{ "12/15/2015" };
	std::istringstream ss(date);
	double month{};
	double day{};
	double year{};
	char junk{};

	ss >> month >> junk >> day >> junk >> year;

	return 0;
}


Hope that helps,

Andy

P.S. It is best to use double over float.
that help now if I can only understand how that work
I found out that i was reading the date wrong to compare
I need a output string in the following format

the date is 12/25/2015
the output format float need to be
1151225.000000

so i can do a proper compare







Hello nickhere,

Well how about something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <iomanip>
#include <string>

int main()
{
	std::string date{ "12/15/2015" };
	double dDate{};

	date.erase(date.begin() + 2);
	date.erase(date.begin() + 4);

	std::cout << '\n' << date;
	dDate = std::stod(date);

	std::cout << std::fixed << std::showpoint << std::setprecision(7);
	std::cout << '\n' << dDate;

	return 0;
}


Andy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>
#include <sstream>

int date_to_int( const std::string& date_str )
{
    std::istringstream stm(date_str) ;
    int mm, dd, yyyy ;
    char sep1, sep2 ;

    // if the pattern (int) / (int) / (int) is matched
    if( stm >> mm >> sep1 >> dd >> sep2 >> yyyy && sep1 == '/' && sep2 == '/' )
    {
        // if required, validate that the values yyyy, mm and dd form a valid date
        yyyy -= 1900 ; // subtract 1900 from the year
        return yyyy*10000 + mm*100 + dd ; // form the int and return it
    }

    else return 0 ; // badly formed date string
}

double date_to_dbl( const std::string& date_str ) { return date_to_int(date_str) ; }

int main()
{
    std::cout << date_to_int( "12/25/2015" ) << '\n'
              << std::fixed << date_to_dbl( "12/25/2015" ) << '\n' ;
}

http://coliru.stacked-crooked.com/a/db716c4bb6e2d0d9
Topic archived. No new replies allowed.