Search code examples
cfgetsscanfgregorian-calendar

Sscanf and fgets proper usage in C - NOTE: edited


I'm trying to make a big program for making a Gregorian calendar but at the moment, I'm just trying to work with a function that parses an inputted date. A few of the functions (sscanf and fgets) I'm not really sure how to use them with the rest of the program. Here is my attempt:

 int main(int arg, char *argv[]) {

    /*
     * Request a date from the user
     * in format DD-MM-YYYY, DD.MM.YYYY or DD/MM/YYYY
     */
    date d; 
    char input_date[20];
    fgets(input_date, 20, stdin); 

    printf("Enter your date of birth in the form DD/MM/YYYY:");
    //fgets(d, 100, stdin);
    sscanf(input_date,"%d", &d.day, &d.month, &d.year);
     if (leapYearFeb(d.year, d.month)) {
                d.day = d.day + 1;
        }

    if (parse_formatted_date(input_date, &d))
        printf("date: %s\ndd = %d, mm = %d, yy = %d\n", input_date, d.day, d.month, d.year);
    return 1;

    return 0; 
}

Here is the date.h header file where I'm calling parse_formatted_date from:

#ifndef DATE_H_
#define DATE_H_

// Define the structure date.
typedef struct {
    int day;
    int month;
    int year;

} date;

// Parses a string 'formatted_date' representing a date
// in format DD-MM-YYYY, DD.MM.YYYY or DD/MM/YYYY
// into a structure date 'parsed_date'.
void parse_formatted_date(char * formatted_date, date * parsed_date) {
    const int ret = sscanf(formatted_date, "%d-%d-%d",
            &parsed_date->day,
            &parsed_date->month,
            &parsed_date->year);
    //printf("Day: %d, Month: %d, Year: %d\n", d.day, d.month, d.year);
    //return ret == 3;

    }
#endif

At the moment, the errors I'm getting are:

main_Assignment4.c: In function ‘main’:
main_Assignment4.c:22: error: void value not ignored as it ought to be

Not sure what these errors mean or how to fix? Thank you!


Solution

  • Modified answer

    // Parses a string 'formatted_date' representing a date
        // in format DD-MM-YYYY, DD.MM.YYYY or DD/MM/YYYY
        // into a structure date 'parsed_date'.
        void parse_formatted_date(char * formatted_date, date * parsed_date)
        {
            sprintf(formatted_date, "%d-%d-%d",
            parsed_date->day,
            parsed_date->month,
            parsed_date->year);
        }
    
    
         int main(int arg, char *argv[]) {
    
            /*
             * Request a date from the user
             * in format DD/MM/YYYY
             */
            date d; 
            char input_date[20];
            printf("Enter your date of birth in the form DD/MM/YYYY:");
            fgets(input_date, 100, stdin);
            sscanf(input_date,"%d/%d/%d", &d.day, &d.month, &d.year);
    
            parse_formatted_date(input_date, &d);
    
            printf("date: %s dd = %d, mm = %d, yy = %d\n", input_date, d.day, d.month, d.year);
            return 0; 
        }