kazinix
kazinix

Reputation: 30153

C - sscanf not working

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!

Upvotes: 13

Views: 13191

Answers (3)

Bee San
Bee San

Reputation: 2675

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.

Upvotes: 8

starrify
starrify

Reputation: 14781

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.

Upvotes: 3

John Weldon
John Weldon

Reputation: 40789

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.

Upvotes: 21

Related Questions