2 years ago

#56769

test-img

Rakesh Solanki

I am trying to take two input dates in vscode in windows in GNU g++ compiler. But I get first date set to zero after I enter second date?

When given the first.date in the first print output the result is good. But as soon as the second scanf line comes into picture it changes the first.date value to zero. So in the last printf line the first.date shows zero always.

Here is sample console text:

Enter first date [DD MM YYY]:15 1 122
First date is 15/1/122
Enter last date [DD MM YYY]:31 12 122
Last date is 31/12/122
First date 0/1/122 and Last date 31/12/122
Enter first date [DD MM YYY]:
////////// code /////////////////////

#include <stdio.h>

// storing date time 

struct DateTime
{
    unsigned char minute;
    unsigned char hour;
    unsigned char date;
    unsigned char month;
    unsigned char year; // 0-255 + 1900
};

int main()
{
    // initializing first and last date
    struct DateTime first;
    struct DateTime last;

    // continous execution loop
    while (1)
    {
        // prompt for first date
        printf("\nEnter first date [DD MM YYY]:");
        scanf("%2u %2u %3u", &first.date, &first.month, &first.year);
        printf("First date is %u/%u/%u", first.date, first.month, first.year);
        // Note: upto this line the first.date is giving proper result

        // clean buffer
        fflush(stdin);

        // prompt for last date
        printf("\nEnter last date [DD MM YYY]:");
        scanf("%2u %2u %3u", &last.date, &last.month, &last.year);
        printf("Last date is %u/%u/%u", last.date, last.month, last.year);

        // giving the results
        // Note: In this line the first.date somehow show zero value
        printf("\nFirst date %u/%u/%u and Last date %u/%u/%u", first.date, first.month, first.year, last.date, last.month, last.year);
    }

    return 0;
}

c

scanf

stdin

fflush

0 Answers

Your Answer

Accepted video resources