C: "Dates and Switches" task; random numbers appear

Hello,

I am on the following task at the moment: https://www.codecademy.com/courses/learn-c/projects/dates-and-switches-c . The final goal: the user prints, for example: “01/01/2021” and the output is: “January 1st, 2021.”

But my code outputs: “January 326441024th, 32767.” I am not sure from where the numbers come from.

The code:

#include <stdio.h>

int main(void) {
  int month, day, year;

  // Standard date form
  printf("Enter date (mm/dd/yyyy): ");
  // Split the user input into 3 variables for the date
  // Don't worry about the `scanf()` below, you'll learn more about these later!
  scanf("0%d, /%d, /%d", &month, &day, &year);

  // Print the month
  switch (month)
  {
    case 1:
    printf("January");
    break;
    case 2:
    printf("February");
    break;
    case 3:
    printf("March");
    break;
    case 4:
    printf("April");
    break;
    case 5:
    printf("May");
    break;
    case 6:
    printf("June");
    break;
    case 7:
    printf("July");
    break;
    case 8:
    printf("August");
    break;
    case 9:
    printf("September");
    break;
    case 10:
    printf("October");
    break;
    case 11:
    printf("November");
    break;
    case 12:
    printf("December");
    break;
    default: 
    printf("Not a month");
    break;
  }

  // Print the day
 printf(" %d", day);

// Print the suffix for a given day

switch (day)
  { 
case 1: case 11: case 21: case 31:
    printf("st, ");
    break;

    case 2: case 22:
    printf("nd, ");
    break;
    case 3: 
    printf("rd, ");
    default: 
    printf("th, "); 
    break;

  }

  // Print the year
  printf("%d.\n", year);
  
  
  return 0;
}

I am not that familiar with scanf, so maybe the issue is something in there… could you give a hint or a suggestion?

Hello.

Format string in first argument of scanf() must be exactly in the same format which user will use for input.

With format 0%d, /%d, /%d and input 01/01/2021 it works like this:

  1. The first character of 01/01/2021 is zero 0? Ok, skip it. Remaining string is 1/01/2021.
  2. We want integer at the start of 1/01/2021. Put it into month variable. Ok, got 1. Remaining string is /01/2021.
  3. Next character of /01/2021 is comma ,? Oh, there is no comma! Stop processing.

So you will get only month from entered date. Other variables will contain random integers.

Try to fix your format string.

Additional info about scanf: https://www.ibm.com/docs/en/i/7.3?topic=functions-scanf-read-data

Hope, I could help.

2 Likes

Thank you, it helped. I have removed the zero and edited the string.