I'm trying to extract a string and an integer out of a string using sscanf
:
#include<stdio.h>
int main()
{
char Command[20] = "command:3";
char Keyword[20];
int Context;
sscanf(Command, "%s:%d", Keyword, &Context);
printf("Keyword:%s\n",Keyword);
printf("Context:%d",Context);
getch();
return 0;
}
But this gives me the output:
Keyword:command:3
Context:1971293397
I'm expecting this ouput:
Keyword:command
Context:3
Why does sscanf
behaves like this? Thanks in advance you for your help!
sscanf() Return valueIf a matching failure occurs before the first receiving argument was assigned, returns zero. If input failure occurs before the first receiving argument was assigned, EOF is returned.
The sscanf() function reads data from buffer into the locations that are given by argument-list . Each argument must be a pointer to a variable with a type that corresponds to a type specifier in the format-string . The sscanf() function returns the number of fields that were successfully converted and assigned.
Syntax: int sscanf ( const char * s, const char * format, ...); Return type: Integer Parameters: s: string used to retrieve data format: string that contains the type specifier(s) … : arguments contains pointers to allocate storage with appropriate type.
scanf() just stops once it encounters a whitespace as it considers this variable "done".
sscanf
expects the %s
tokens to be whitespace delimited (tab, space, newline), so you'd have to have a space between the string and the :
for an ugly looking hack you can try:
sscanf(Command, "%[^:]:%d", Keyword, &Context);
which will force the token to not match the colon.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With