0

hey guys ok i wrote this code which would check if a get request is proper but at the last comparison it doesn't give me the expected result thank you in advance the problem is in the last if statement it return false when it should return true

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

int main()
{
    char* string="GET /cats.html HTTP/1.1\r\n";
    if(strncmp(string,"GET ",4)==0)
    {
        printf("hello");
        if(string[4]=='/')
        {
            printf(",\n");
            char* string1=strchr(string,'.');
            string1=strchr(string1,' ');
            printf("%s",string1);
            if(string1!=NULL)
            {
                if(*string1==" HTTP/1.1\r\n")
                {
                    printf("world\n");
                }
            }
        }
    }
} 

2 Answers2

4

The line:

if(*string1==" HTTP/1.1\r\n")

does not compare whether two strings are equal.

type of string1 is char*. Hence type of *string1 is char.

Hence, you are comparing a char with a char const*, which is far from what you expected.

Even using

if(string1==" HTTP/1.1\r\n")

will not give you the expected result since it will compare two pointers for equality, which will be false in this use case all the time.

What you need to use is the library function to compare two strings.

if( strcmp(string1, " HTTP/1.1\r\n") == 0)
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

Because you are not comparing strings, you are comparing pointers to strings.

The proper comparison would be:

if(!strcmp(string1," HTTP/1.1\r\n")) {
    ...
}
Serge
  • 6,088
  • 17
  • 27