首页 > 解决方案 > 使用 strcmp 从服务器缓冲区读取字符串

问题描述

我正在尝试构建一个 tcp 服务器来从套接字缓冲区读取字符串。客户端的缓冲区,使用如下代码操作:

n = 0;
    do {
        sign = getchar();
        if(n >= 253) break;
        if (sign =='\n') break;
        buffer[n ++] = sign;
    } while (1);
    buffer [n] = 0;

服务器代码在循环中从套接字读取字符串

bzero(buffer,255);
n = read(sock,buffer,255);
printf("Here is the message: %s\n",buffer);

到目前为止一切正常。

    for(int k = 0; k < sizeof(buffer); k++) {
        string[i ++] = buffer[k];
        if (buffer[k] == 0 ) break;
        if (buffer[k] == '\n' ) break;
    }
    printf("Here is the string: %s\n",string);

    char **dict = dictionary();
    cmp(string, dict);
    free_dictionary(dict);
    exit(0);
}
else close(newsockfd);

char **dictionary() // dictionary code
{
    char **dict = (char**)malloc(sizeof(char*) * 5);
    int i = 0;
    for(i = 0; i < 5; i++)
        dict[i] = (char*)malloc(sizeof(char) * 255);
    strcpy(dict[0], "mark");
    strcpy(dict[1], "ala");
    strcpy(dict[2], "wojtek");
    strcpy(dict[3], "tom");
    strcpy(dict[4], "john");
    return (dict);
}
void free_dictionary(char **dict) 
{
    for (int i = 0; i < 5; i++)
        free(dict[i]);
    free(dict);
}

int cmp(char *s1, char *s2[5]) //comparison function
{
    int k = 0;
    int n = 0;
    do {
        if (strcmp(s1, s2[k]) == 0)
        n++;
        k++;
    } while(k < 5);
    if (n > 0)
        printf("Found %d", n);
    else
        printf("Nothing found %d\n", n);
    return 0;
}

一切似乎都很好,除了 strcmp 似乎不起作用的事实。<string.h> 包括在内。对于发送“ala”的客户端,输出为:“这是 s2 mark 这是 s2 ala 这是 s2 wojtek 这是 s2 tom 这是 s2 john 没有找到 0”

标签: cstrcmp

解决方案


推荐阅读