开发者

Buffer comparing (without new line character) with a string

How to compare a buffer without new line character with a string?

strcmp(buffer,"change") is not returnin开发者_开发问答g 0.


strncmp is the function you can use to do that.


From your post I assume you have a \n in 'buffer' so this will fail

strcmp(buffer,"change")

In order to compare write instead

strncmp(buffer,"change",strlen("change")) 

or better

char keyword[] = "change";
strncmp(buffer,keyword,strlen(keyword)


Other than the suggested strncmp, you can remove the '\n' from buffer before comparing ...

char buffer[WHATEVER];
if (!fgets(buffer, sizeof buffer, stdin)) /* uh oh */ exit(EXIT_FAILURE);

{ /* validate buffer and remove trailing '\n' */
    size_t buflen;
    buflen = strlen(buffer);
    if (!buflen) /* oh uh */ exit(EXIT_FAILURE);
    if (buffer[buflen - 1] != '\n') /* oh uh */ exit(EXIT_FAILURE);
    buffer[buflen - 1] = 0;
}

if (strcmp(buffer, "change") == 0) /* "change" found */;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜