0

I've looked at other posts about reading strings from the keyboard with C and haven't found an answer to this question, or perhaps I didn't recognize the answer.

I need for the user to be able to enter a formatted timestamp from the keyboard and then use that to set some process parameters on a system. Here is my sandbox code

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <time.h>

void main ()
{

  unsigned int UserDayChoice;
    unsigned int UserMonthChoice;
    unsigned int UserYearChoice;
    unsigned int UserHourChoice;
    unsigned int UserMinutesChoice;  
    
    printf("Enter your desired planting date in this format -> MM/DD/YYYY hh:mm.\n");
    printf("For example 04/19/2022 08:00\n");
    
    scanf("%d/%d/%d %d:%d",&UserMonthChoice, &UserDayChoice, &UserYearChoice, &UserHourChoice, &UserMinutesChoice);
    printf("You entered %d/%d/%d %d:%d \n",UserMonthChoice, UserDayChoice, UserYearChoice, UserHourChoice, UserMinutesChoice);
          
}

I really don't like this approach but it does work whereas I could never get fgets from stdin to work for me. However, when I run it and enter a string like this at the keyboard

10/10/2022 08:00

The output of the

printf("You entered %d/%d/%d %d:%d \n",UserMonthChoice, UserDayChoice, UserYearChoice, UserHourChoice, UserMinutesChoice);

is

10/10/2022 08:0

The last character is truncated. It's probably very obvious, but I can't figure out what it is. Help would be appreciated greatly!

Better alternatives are also welcome, although this does give me the values I need to use with the mktime function later in my control program.

  • Use `strptime`. – Cheatah Oct 04 '22 at 18:57
  • Seconds are integer 0 here. When you print integer 0, it prints 0, not 00. – hyde Oct 04 '22 at 19:14
  • printf can print what you want (leading zeroes), read its docs... – hyde Oct 04 '22 at 19:16
  • @hyde Yep! What a dunce I am. I don't need the leading zeros but just totally missed that was the issue. If I had used a test value like 08:10, this post would have never happened! Thank you! – WalterCEden Oct 04 '22 at 19:41
  • You should get 8:0 not 08:0. If you want leading zeros use `%02d` format specifier. You might also more usefully use time.h create a `tm` struct, convert that to a `time_t` then use `strftime()` to output in a variety of formats. – Clifford Oct 04 '22 at 22:04

0 Answers0