Lobscurite Lobscurite - 4 months ago 98
C Question

CS50 Pset6 error 405 keeps on printing server.c

So my code no matter what returns error 405(once the test that only two spaces are in the request-line is passed). Which makes me believe I have made an error in creating a code to determine that "GET" is in fact the first word. This is all my code leading up to the "check" that the method type is "GET" or any capitalization thereof.

int s;
s=0;
int i=0;
for(int q=0; q<strlen(line); q++)
{
if(line[q] == ' ')
s++;
}
if(s!=2)
{
error(400);
return false;
}
if((line[i] != 'g' || line[i] != 'G') || (line[i+1] != 'e' || line[i+1] != 'E') || (line[i+2] != 't' || line[i+2] != 'T')||
(line[i+3] != ' ' ))
{
error(405);
return false;
}


Any reason this would always return false? I have int i initialized to zero

Answer

Any reason this would always return false?

Reason :

  • consider the if statement as :

    if(expression_1 || expression_2 || expression_3 || expression_4)
    //where
    //expression_1 is (line[i] != 'g' || line[i] != 'G')
    //expression_2 is (line[i] != 'e' || line[i] != 'E')
    //expression_3 is (line[i] != 't' || line[i] != 'T')
    //expression_4 is (line[i] != ' ')   
    
  • let's consider line as GET

  • Now, expression_1 is always evaluated to be true even though line[i] == G because line[i] != 'g' is true. Therefore, (line[i] != 'g' || line[i] != 'G') is true as true || false == true

  • Now further expressions are not evaluated as || is a lazy operator and it stops evaluation on first true occurrence as true || anything == true

  • Thus, if block is always entered and false is always returned.


Solution :

  • Change the if in your code :

    if((line[i] != 'g' || line[i] != 'G') || (line[i+1] != 'e' || line[i+1] != 'E') || (line[i+2] != 't' || line[i+2] != 'T') || (line[i+3] != ' '  ))
    
  • To the following :

    if((line[i] != 'g' && line[i] != 'G') || (line[i+1] != 'e' && line[i+1] != 'E') || (line[i+2] != 't' && line[i+2] != 'T') || (line[i+3] != ' '  ))
    
  • Here line[i] != 'g' && line[i] != 'G' gets evaluated to false as true && false == false and further expressions are checked till a true is encountered.

  • If no true is encountered then if() block is not entered

Further,

  • As @twalberg has suggested in the comment, it'd be much readable and understandable if you use your if statement as if( !strncasecmp(line, "get ", 3) ) by including the strings.h header file

  • Know more about strncasemp() function here : click