Sarah cartenz
Sarah cartenz

Reputation: 1313

Getting the correct sscanf format to print a string and integers

How should the sscanf argument look like if I want the output of the print statement to be: Saturday March 25 1989

In other words I want the date to contain both Saturday AND March. I tried different sscanf format options but the print statement usually comes out gibberish.

int day, year;
char date[50], dtm[100];
strcpy( dtm, "Saturday March 25 1989" );
sscanf( dtm, "%s %d %d", date, &day, &year );

printf("%s %d %d\n", date, day, year );

Upvotes: 0

Views: 118

Answers (1)

bruno
bruno

Reputation: 32586

in sscanf %s will get only Saturday because of the space then %d will try to extract an int from March and of course cannot

but you can do :

sscanf( dtm, "%[^0-9] %d %d", date, &day, &year );

or better

sscanf( dtm, "%49[^0-9] %d %d", date, &day, &year );

to not take the risk to write out of date (49 rather than 50 to let the space for the ending null character).

So

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

int main()
{
  int day, year;
  char date[50], dtm[100];
  strcpy( dtm, "Saturday March 25 1989" );
  if (sscanf( dtm, "%49[^0-9]%d%d", date, &day, &year ) == 3) /* remove useless spaces in format */
  
    printf("'%s' %d %d\n", date, day, year ); /* use '%s' to show all from date */
  return 0;
}

Compilation and execution:

pi@raspberrypi:/tmp $ gcc -Wall c.c
pi@raspberrypi:/tmp $ ./a.out
'Saturday March ' 25 1989
pi@raspberrypi:/tmp $ 

as you can see the date memorizes the separating space after the date up to the day number, it is not possible to avoid that in your case because the length of the date is variable, but you can bypass the possible spaces before using sscanf( dtm, " %[^0-9]%d%d", date, &day, &year ); :

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

int main()
{
  int day, year;
  char date[50], dtm[100];
  strcpy( dtm, "   Saturday March 25 1989" );
  if (sscanf( dtm, " %49[^0-9]%d%d", date, &day, &year ) == 3)
    printf("'%s' %d %d\n", date, day, year );
  return 0;
}

Compilation and execution :

pi@raspberrypi:/tmp $ gcc -Wall c.c
pi@raspberrypi:/tmp $ ./a.out
'Saturday March ' 25 1989
pi@raspberrypi:/tmp $ 

Out of that dtm is useless and you can do directly :

if (sscanf("   Saturday March 25 1989",
    " %49[^0-9]%d%d", date, &day, &year ) == 3)

Upvotes: 2

Related Questions