scanf reading 3 numbers and 1 string

I've written a small peace of code and it behaves very strange from my point of view. So the program reads date and 2015-11-30 Mo. Then I will need to get day of week number by comparing with array of values. Here is the code:

#include <stdio.h>
#include <stdio.h>
#include <string.h>

typedef struct Date
{
    int d, m, y;
} date;

int main(void) {

    char wdays[][7] = {"Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"};
    date dt;
    char wday[2];
    printf("Input date and day of week.\nFor example: 2015-11-30 Mo\n");
    scanf("%d-%d-%d %2c\n", &dt.y, &dt.m, &dt.d, wday);
    printf("%d-%d-%d %s\n", dt.y, dt.m, dt.d, wday);
    if (strcmp(wdays[0], wday) == 0) printf("Compare Ok");
    printf("%d\n", wday[2]);

    return 0;
}

The problem is that wday[2] is not empty and comparing to values from wdays fails(I input 2015-11-30 Mo). Could you please explain me why is it not empty? I declared it to be 2 chars length and I read in 2 chars using scanf.

Additional questions: 1) If I put "char wday[1];" instead of "char wday[2];" then wday contains only 2 characters, but dt.d reads in wrong and I receive 111(which is code of letter "o") instead of 30.

2) I also tried to read in like this

scanf("%d-%d-%d %s\n", &dt.y, &dt.m, &dt.d, wday);

But dt.d also reads in wrong even with "char wdays[2];"

So I feel like I'm missing something about scanf or char arrays. Could you please help me to find it out?

Upvotes: 0

Views: 1166

Answers (2)

Keshava GN
Keshava GN

Reputation: 4255

Do the following changes:

  1. As wday string needs to store 3 bytes, use char wday[3];
  2. scanf - Change to %2s for wday.
  3. printf at the end - use %s (optional)

Here's the code:

#include <stdio.h>
#include <stdio.h>
#include <string.h>

typedef struct Date
{
    int d, m, y;
} date;

int main(void) {

    char wdays[][7] = {"Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"};
    date dt;
    char wday[3];
    printf("Input date and day of week.\nFor example: 2015-11-30 Mo\n");
    scanf("%d-%d-%d %2s\n", &dt.y, &dt.m, &dt.d, wday);
    printf("%d-%d-%d %2s\n", dt.y, dt.m, dt.d, wday);
    if (strcmp(wdays[0], wday) == 0) printf("Compare Ok\n");
    printf("%s\n", wday);

    return 0;
}

Upvotes: 1

Haris
Haris

Reputation: 12270

Read wday using the string %s conversion character, instead of %c.

scanf("%d-%d-%d %2s\n", &dt.y, &dt.m, &dt.d, wday);

Upvotes: 1

Related Questions