Problem with strcmp usage
here is code
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;
}
}
actually the input to the function process is
i/p: regular:ddf
but when i extract the token using strtok func and display s it is printing as "regular" correctly, but when i use "s" in strcmp(s,"regular")==0 it is not working. what is the problem????
Given your input, the s
parameter to strcmp
is
" regular"
not
"regular"
Thus, no match, and, as a result, the code in the if
block never runs and your while
loop will never terminate.
Here's a function (and a complete program showing how to use it) that does what I think you want. Given the input of "i/p: regular:ddf" it prints:
Token found: "i/p" Token found: "regular" Regular! Token found: "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
}
One big drawback to this approach, however, if that you can't call strtok
anywhere else in the loop because this function relies on the internal state that is stored by strtok
when it calls strtok
with a NULL argument.
精彩评论