2011-10-25 26 views
10

我想提取字符串,並使用sscanf一個字符串的整數Ç - 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; 
} 

但是這給了我輸出:

Keyword:command:3 
Context:1971293397 

我預計此輸出中:

Keyword:command 
Context:3 

爲什麼sscanf的行爲也是這樣嗎?在此先感謝您的幫助!

+1

有沒有很好的理由你不檢查'sscanf'的結果? –

回答

14

sscanf預計%s令牌被空格分隔(製表符,空格,換行),所以你必須有串和一個空格:

一個難看的修改,您就可以嘗試:

sscanf(Command, "%[^:]:%d", Keyword, &Context); 

這將迫使令牌不符合冒號。

+0

你的意思是,我無法使用「:」作爲分隔符? – dpp

+0

所以不可能從「command:3」中提取字符串和整數? – dpp

+0

是的,它是:'sscanf(命令,「%7s:%d」,關鍵字和上下文);'另一方面,它只接受長度爲7個字符的命令。 – fritzone

2

在這裏使用%[公約。看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; 
} 

這給 「此處命令:3」 作爲它的輸出。

5

如果你不是特別使用sscanf,你總是可以使用strtok,因爲你想要的是標記你的字符串。

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); 

在我看來這更具可讀性。

+0

謝謝,但我想研究'sscanf'。 – dpp

+0

我已將此用於我的代碼,謝謝。 – dpp