Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - sscanf not working

Tags:

c

scanf

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!

like image 806
dpp Avatar asked Oct 25 '11 09:10

dpp


People also ask

What happens if sscanf fails?

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.

How does sscanf work in C?

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.

What is correct syntax for sscanf () function?

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.

Does sscanf stop at whitespace?

scanf() just stops once it encounters a whitespace as it considers this variable "done".


1 Answers

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.

like image 137
John Weldon Avatar answered Sep 21 '22 04:09

John Weldon