How to convert a string to a date component in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <sstream>

struct Date
{
    int year;
    int month;
    int day;
};

int main()
{
    std::string dateStr = "2026-10-20";

    Date d;

    char dash1, dash2;

    std::stringstream ss(dateStr);

    ss >> d.year >> dash1 >> d.month >> dash2 >> d.day;

    std::cout << d.year << ' '
              << d.month << ' '
              << d.day << '\n';
}


/*
run:

2026 10 20

*/

 



answered Oct 21 by avibootz
...