Given the data in the format of the following string:
"(Saturday) March 25 1989"
I need to parse this string and store each element in the corresponding variables. The variable should contain:
day = 25
year = 1989
day = "Saturday"
month = "March"
I have tried to parse the string with the following code but it doesn't seem to work right.
int day, year;
char weekday[20], month[20], dtm[100];
strcpy( dtm, "(Saturday) March 25 1989" );
sscanf( dtm, "(%s[^)] %s %d %d", weekday, month, &day, &year );
printf("%s %d, %d = %s\n", month, day, year, weekday );
The code has the following output for some reason:
0, 16 = Saturday)
I'd appreciate any help.
CodePudding user response:
I think the correct format should be this:
sscanf( dtm, " ([^)]) s %d %d", weekday, month, &day, &year );
// ^ ^ ^ ^
// | | | limit the number of chars (sizeof month - 1)
// | | the end ) should be matched
// | no 's' and limit the number of chars (sizeof weekday - 1)
// eat whitespaces (like newline)
CodePudding user response:
You're mixing up %s
and %[
, which are separate specifiers. Furthermore, %[
doesn't eat the stopping character(s) (in this case )
), you'll have to do it manually.
With %[
, your sscanf
call should look like:
sscanf( dtm, "(%[^)]) %s %d %d", weekday, month, &day, &year );
// ^ Eat )
// ^Scan until )
You'll also want to handle whitespace so that even an input like ( Saturday )
will only scan Saturday
:
#define WHITESPACE " \r\n\t\v\f"
sscanf( dtm, " ( %[^)"WHITESPACE"] ) %s %d %d", weekday, month, &day, &year );
And you'll also want to limit the number of characters that should be scanned for a string so you don't suffer a buffer overflow, but Ted's answer already shows how to do this.