Learning how to parse strings and use structs in C -
i'm trying mess around structs , pointers in c. want accomplish user enter date in format dd-mm-yyyy in main(), parse string formatted_date. i've read few suggestions on how don't understand how apply it. appreciated. thanks!
#ifndef date_h_ #define date_h_ // define structure date. typedef struct { int tm_mday; int tm_month; int tm_year; } date; // parses string 'formatted_date' representing date // in format dd-mm-yyyy, dd.mm.yyyy or dd/mm/yyyy // structure date 'parsed_date'. void parse_formatted_date(char * formatted_date, date * parsed_date) { }
you use sscanf()
parse formated date string this:
int parse_formatted_date(const char *formatted_date, date *parsed_date) { const int ret = sscanf(formatted_date, "%d-%d-%d", &parsed_date->tm_mday, &parsed_date->tm_month, &parsed_date->tm_year); return ret == 3; }
here full test program:
#include <stdio.h> #include <stdlib.h> typedef struct { int tm_mday; int tm_month; int tm_year; } date; int parse_formatted_date(const char *formatted_date, date *parsed_date) { const int ret = sscanf(formatted_date, "%d-%d-%d", &parsed_date->tm_mday, &parsed_date->tm_month, &parsed_date->tm_year); return ret == 3; } int main(int argc, char *argv[]) { date d; char *formatted_date = "06-03-2014"; if (parse_formatted_date(formatted_date, &d)) printf("date: %s\ndd = %d, mm = %d, yy = %d\n", formatted_date, d.tm_mday, d.tm_month, d.tm_year); exit(exit_success); }
Comments
Post a Comment