Date parser in C

Asked

Viewed 334 times

0

I was doing some tests to do parsers date and made this example based on a program that formats through the sscanf() with a string constant defined but not understood well where is the error:

#include <cstring>
#include <iostream>

int main()
{
   int day, year;
   char weekday[20], month[20], dtm[100];

   printf
    (
     "\n\tDigite Dia Mes a ano em string"
     "\n\tex.(Saturday March 25 1989): "
    );

   scanf("%s80[^\n]",&dtm);

   sscanf(dtm, "%s %s %d  %d", &weekday, &month, &day, &year);

   printf("%s %d, %d = %s\n", month, day, year, weekday);

   return 0;
} 

/*
 Input: 
   Saturday March 25 1989

 Output:

  `l 0, 0 = Saturday 

where Output should be:

March 25 1989 Saturday */

  • 1

    Is that a question or an answer?

  • is a question wanted to understand which error is that I forgot to describe trying to format the code here but I could not there someone formatted it..

  • actually output ai should be: March 25 1989 Saturday

  • Edit your question to be clear to everyone, it should attract more people to answer.

  • This code does not even compile. At least in a good compiler.

  • C or C++? I believe you made a slight mistake in marking the language

  • @dark777 The answer solved your question? Do you think you can accept it? See [tour] if you don’t know how to do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

  • the answer that helped me has already been voted...

Show 3 more comments

1 answer

1

This isn’t exactly a parse date, is a string with 4 separations between spaces that in theory the last 2 must be numbers, nothing more than this.

Actually the error is in the data entry. The default of scanf() is wrong.

#include <stdio.h>

int main() {
    int day, year;
    char weekday[20], month[20], dtm[100];
    printf(
        "\n\tDigite Dia Mes a ano em string"
        "\n\tex.(Saturday March 25 1989): "
    );
    scanf("%[^\n]s80", dtm);
    printf("%s\n", dtm);
    sscanf(dtm, "%s %s %d  %d", weekday, month, &day, &year);
    printf("%s %d, %d = %s\n", month, day, year, weekday);
} 

Behold working in the ideone, and in the repl it.. Also put on the Github for future reference.

  • now it worked... funfou legal actually I was more inspired to search about it based on a program I have in D language. as example: import Std.format; void main() { string s = "Name Surname 18"; string name, surname; int age; formattedRead(s, "%s %s %s", &name, &surname, &age); // %s selects a format based on the corresponding argument’s type }

  • Well, you removed the scanf() entirely? How will the data arrive in the dtm?

  • @Wtrmute I copied the wrong code :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.