0

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;
}
Evg
  • 25,259
  • 5
  • 41
  • 83
  • 1
    `fflush(stdin)` can lead to undefined behavior. – kiner_shah Jan 16 '22 at 10:11
  • 3
    Why are you using a c++ compiler to compile a c program? Why not use `gcc` instead? Also, add these compiler options: `-Wall -Wextra -Werror -pedantic-errors` and you'll get a lot of useful hints of things to fix in your program. – Ted Lyngmo Jan 16 '22 at 10:13
  • From the [scanf manual](https://linux.die.net/man/3/scanf) describing the `u` conversion: "Matches an unsigned decimal integer; **the next pointer must be a pointer to unsigned int.**". You are passing pointer to `unsigned char` which violates that requirement. – kaylum Jan 16 '22 at 10:19
  • You have to use `%hhu` for all the `scanf` specifier: https://godbolt.org/z/jGM41M7vz – mch Jan 16 '22 at 10:24
  • %hhu gives the same trouble, while I tried to change the struct members to unsigned short int with %hu specifier and it works. This means the error has something to do with the correct format specifier but %hhu does not work. – Rakesh Solanki Jan 16 '22 at 12:04

0 Answers0