Синтаксический анализ выдает ошибку в check50 pset6

#cs50

#cs50

Вопрос:

Я закодировал функцию parse для этого pset, но check50 проверяет только как действительное следующее:

 :) server.c exists
:) server compiles
:( HTTP/1.0 returns error code 505
    expected output, but not "HTTP/1.1 400 Bad RequestrnContent-Typ..."
:( Method of 'abcGET' returns error code 405
    expected output, but not "HTTP/1.1 400 Bad RequestrnContent-Typ..."
:( Method of 'GETabc' returns error code 405
    expected output, but not "HTTP/1.1 400 Bad RequestrnContent-Typ..."
:( request-target without starting '/' returns error code 501
    expected output, but not "HTTP/1.1 400 Bad RequestrnContent-Typ..."
:( request-target of abc/hello.php returns error code 501
    expected output, but not "HTTP/1.1 400 Bad RequestrnContent-Typ..."
:( Requesting cat.exe returns error code 501
    expected output, but not "HTTP/1.1 400 Bad RequestrnContent-Typ..."
:( Requesting non-existant file returns error code 404
    expected output, but not "HTTP/1.1 400 Bad RequestrnContent-Typ..."
:) Requesting request-target with " returns error code 400
:) Two spaces after GET returns error code
:) A space within the request target returns error code
:) Two spaces before HTTP/1.1 returns error code
  

Таким образом, в основном работает только проверка пробелов. Я хотел бы получить некоторое представление о том, в чем проблема в моем коде при сравнении строк. Я предполагаю, что что-то не так с использованием функций, но после нескольких часов исследования я все еще не вижу решения. Я полный новичок, и я был бы действительно признателен за некоторую помощь. Спасибо

Это код для моей функции синтаксического анализа

 bool parse(const char* line, char* abs_path, char* query)
{
    // TODO
    // Get the lenght of line
    int l = strlen(line);

    // Store the place in the string 
    int a = 0;

    // Stores number of total spaces
    int spaces = 0;

    // Iterate in line
    for (int i = 0; i < l; i  )
    {// Look for spaces
        if (isspace(line[i]) == 0)
        {
            spaces  ;
        }
    }
    // If there are more than the 2 required spaces
    if (spaces > 2)
    {
        error(400);
        printf("400 Bad Requestn");
        return false;
    }
    // If request - target doen't begin with "/"

    // Look for the fist space
    for (int i = 0; i < l; i  )
    {// Look for space
        if (isspace(line[i]) == 0)
        {
            a = i   1;
            break;
        }
    }

    if (line[a] != '/')
    {
        error(501);
        printf("501 not implementedn");
        return false;
    }


    {
        error(405);
        printf("405 Method Not Allowedn");
        return false;
    }

    // If request-target contains "
    // Will store position of second space
    int b = 0;
    // Look for the second space
    for (int i = a; i < l; i  )
    {
        if (isspace(line[i]) == 0)
        {
            b = i;
            break;
        }
    }
    // Find if there is a " in request-target
    for (int i = a; i < b; i  )
    {
        if ( line[i] == '"')
        {   
            error(400);
            printf("400 Bad Requestn");
            return false;
        }
    }

    // If HTTP version isn't HTTP/1.1
    char http[7] = "";
    for (int i = b   1; i < (b   1)   7/*Chars 
    from the second space till the end of HTTP/1.1*/;i  )
    {
        http[i] = line[i];
    }

    if (strcmp(http, "HTTP/1.1") != 0)
    {
        error(505);
        printf("505 HTTP Version Not Supportedn");
        return false;
    }

    // Store absolute-path at the address in abs_path and the query string at query

    // Separate the query
    // String to store the query
    char query2[8190   1] = "";

    // Store the position in line where the query string starts
    int c = 0;
    // Counter for query array
    int q = 0;
    for (int i = b - 1/*before the space after the query*/; i > a/*after the first space*/;i--)
    {
        if (line[i] == '=')
        {
            c = i - 1;
            break;
        }

    }
    // Pass the string to query2
    for (int i = c; i < (b - 1); i  )
    {
        query2[q] = line[i];
        q  ;
    }
    // If there is no query, make query2 empty
    if (query2[0] != 'q')
    {
        strcpy(query2, "");
    }

    // Allocate query2 and query at the heap
    query = malloc(sizeof(query2));

    // Copy query2 to query
    strcpy(query, query2);

    // Separate absolute path
    // Declare char array to store absolute path
    char abs1[8190   1] = "";

    // Make space at the heap

    abs_path = malloc(sizeof(abs1));

    for (int i = a /*where the / after the first space starts*/; i < (c - 1);
    i  )
    {
        abs1[i] = line[i];
    }

    // Copy abs to abs_path
    strcpy(abs_path, abs1);

    return true;


}
  

Ответ №1:

Синтаксический анализ всегда возвращает «400 ошибочных запросов», что указывает на то, что условие:

 if (spaces > 2)
  

всегда присваивается значение true, это потому, что строка содержит два или более пробела, но это потому, что формат http-запроса требует, чтобы пробел отделял метод от запроса, а другой пробел отделял запрос от http-версии.

Вам нужно искать два последовательных пробела, а не два пробела во всей строке.

И вам следует использовать рекомендуемые функции вместо множества циклов for.

Комментарии:

1. Спасибо за вашу помощь @Daniel P., я рассмотрю это