13

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!

kazinix
  • 28,987
  • 33
  • 107
  • 157

3 Answers3

21

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.

John Weldon
  • 39,849
  • 11
  • 94
  • 127
8

If you aren't particular about using sscanf, you could always use strtok, since what you want is to tokenize your string.

    char Command[20] = "command:3";

    char* key;
    int val;

    key = strtok(Command, ":");
    val = atoi(strtok(NULL, ":"));

    printf("Keyword:%s\n",key);
    printf("Context:%d\n",val);

This is much more readable, in my opinion.

Bee San
  • 2,605
  • 2
  • 20
  • 19
3

use a %[ convention here. see the manual page of scanf: http://linux.die.net/man/3/scanf

#include <stdio.h>

int main()
{
    char *s = "command:3";
    char s1[0xff];
    int d;
    sscanf(s, "%[^:]:%d", s1, &d);
    printf("here: %s:%d\n", s1, d);
    return 0;
}

which gives "here:command:3" as its output.

starrify
  • 14,307
  • 5
  • 33
  • 50