2011-07-09 34 views
-2

這裏是代碼問題使用strcmp用法

void process(char *input) 
{ 
char *s; 
char s1[100]; 
s=strtok(input,":"); 

while(1) 
{ 
    if(strcmp(s,"regular")==0)// the strcmp is not working 
    { 
    s=strtok(NULL,","); 
    if(s==NULL) 
    break; 
    } 
} 

實際上輸入到函數處理是

i/p:   regular:ddf 

但是當我使用的strtok FUNC和顯示• 正在打印爲「提取令牌正常「,但是當我在strcmp(s,」regular「)中使用」s「時== 0 它不起作用。問題是什麼????

+2

if if'if' failed,you stuck in a infinite loop – pmg

+0

@pmg y if if failed?對於這個輸入:常規:df, – tks

+0

是''i/p:「'輸入的一部分嗎? – pmg

回答

1

鑑於你輸入時,s參數strcmp

"   regular" 

"regular" 

因此,不匹配,並且,其結果是,在if塊中的代碼永遠不會運行,您的while循環將永不終止。

0

這是一個功能(和一個完整的程序,顯示如何使用它),做我認爲你想要的。鑑於輸入 「I/P:常規:DDF」 它打印:

令牌發現: 「I/P」 令牌發現: 「常規」 常規! 令牌發現:「DDF」

#include <stdio.h> 
#include <string.h> 

void process(char * input) 
{ 
    char * s = strtok(input, ": "); // Get first token. Colon AND space are delimiters. 
    while(1) 
    { 
     if (s == NULL) 
     { 
      break; // No more tokens. 
     } 

     printf("Token found: \"%s\"\n", s); 
     if(strcmp(s,"regular")==0) 
     { 
      printf("Found \"regular\" token.\n"); 
     } 

     s = strtok(NULL, ": "); // Get next token. 
    } 
} 

int main(int argc, char **argv) 
{ 
    char str[] = "i/p:   regular:ddf"; 
    process(str); // Warning: process(str) will modify str 
} 

的一大缺陷,以這種方法,但是,如果你不能在循環中調用strtok其他地方,因爲這個功能依賴於由存儲內部狀態strtok當它調用strtok與NULL參數。