CS50 Pset6 error 405 keeps on printing server.c -


so code, no matter what, returns error 405 (once test 2 spaces in request-line passed). makes me believe have made error in creating code determine "get" in fact first word. code leading "check" method type "get" or 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 return false? have int i initialized 0.

any reason return false?

reason :

  • consider if statement :

    if(expression_1 || expression_2 || expression_3 || expression_4) //where //expression_1 (line[i] != 'g' || line[i] != 'g') //expression_2 (line[i] != 'e' || line[i] != 'e') //expression_3 (line[i] != 't' || line[i] != 't') //expression_4 (line[i] != ' ')    
  • let's consider line get

  • now, expression_1 always evaluated true though line[i] == g because line[i] != 'g' true. therefore, (line[i] != 'g' || line[i] != 'g') true true || false == true

  • now further expressions not evaluated || lazy operator , stops evaluation on first true occurrence true || == true

  • thus, if block entered , false returned.


solution :

  • change if in 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 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 false true && false == false , further expressions checked till true encountered.

  • if no true encountered if() block not entered

further,

  • as @twalberg has suggested in comment, it'd readable , understandable if use if statement if( !strncasecmp(line, "get ", 3) ) including strings.h header file

  • know more strncasemp() function here : click


Comments