suvitha
suvitha

Reputation: 113

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 returning 0.

Upvotes: 0

Views: 3640

Answers (3)

pmg
pmg

Reputation: 108938

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 */;

Upvotes: 0

AndersK
AndersK

Reputation: 36082

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)

Upvotes: 0

Zimbabao
Zimbabao

Reputation: 8240

strncmp is the function you can use to do that.

Upvotes: 1

Related Questions