Nathaniel King
Nathaniel King

Reputation: 29

Entering date as a char in C, can't work out how to avoid the /

#include <stdio.h>

int main(void)
{
    char day[3] = {""};
    char month[3] = {""};
    char year[5] = {""};

    printf("Date of Birth: ");
    scanf("%s[^/]%*c%s[^/]%*c%s", &day, &month, &year);
    printf("\n1. %s", day);
    printf("\n2. %s", month);
    printf("\n3. %s", year);
}

I'm trying to enter the date and discarding the /. Currently, the whole entry gets stored into char day[3] and the other three chars are left blank.

I am using char because I want to keep the leading zeros and I am using the strings to make a file name without the /.

Upvotes: 2

Views: 69

Answers (1)

dbush
dbush

Reputation: 223972

The first %s in your format string is capturing everything up to the first whitespace character, which is your whole date string. The [^/] the immediately proceeds it it matching exact characters.

What you want is to use the %[ format specifier to grab characters up to a /.

scanf("%2[^/]%*c%2[^/]%*c%4s", &day, &month, &year);

Also note the inclusion of a field width to each to prevent writing past the end of the given buffers.

Upvotes: 5

Related Questions