Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何比较收到的答案?_C_Comparison - Fatal编程技术网

C 如何比较收到的答案?

C 如何比较收到的答案?,c,comparison,C,Comparison,我用C编写了一个简单的echo服务器,如果服务器收到quitword,我想停止它 int n; char buffer[256]; while(strcmp(buffer,"quit") != 0) { n = read(sock,buffer,255); if (n < 0) { perror("ERROR reading from socket"); exit(1);

我用C编写了一个简单的echo服务器,如果服务器收到
quit
word,我想停止它

    int n;
    char buffer[256];
    while(strcmp(buffer,"quit") != 0)
    {
        n = read(sock,buffer,255);
        if (n < 0)
        {
        perror("ERROR reading from socket");
        exit(1);
        }

        printf("Here is the message: %s\n",buffer);
        printf("%d-%d\n", sizeof(buffer), strcmp(buffer,"quit"));

        n = write(sock,"I got your message",18);
        if (n < 0) 
        {
        perror("ERROR writing to socket");
        exit(1);
        }
  }
intn;
字符缓冲区[256];
while(strcmp(缓冲区,“退出”)!=0)
{
n=读取(sock,缓冲区,255);
if(n<0)
{
perror(“从套接字读取错误”);
出口(1);
}
printf(“这是消息:%s\n”,缓冲区);
printf(“%d-%d\n”、sizeof(缓冲区)、strcmp(缓冲区,“退出”);
n=写(sock,“我收到你的消息”,18);
if(n<0)
{
perror(“写入套接字时出错”);
出口(1);
}
}

如何将接收到的缓冲区与字符串进行比较

缓冲区可能不是以0结尾的,因此使用“字符串”比较函数是错误的。您应该尝试使用
strncmp
memcmp


另外,在
while
条件下,您在实际读取
缓冲区之前进行测试。除了其他人所说的之外,您的程序的行为是未定义的:当进入循环时,您在初始化之前从
缓冲区读取。

void strip(char *s) {
    char *p2 = s;
    while(*s != '\0') {
        if(*s != '\t' && *s != '\n' && *s != '\r') {
                *p2++ = *s++;
        } else {
                ++s;
        }
    }
    *p2 = '\0';
}

上述代码有什么问题?@iUngi:。。您从哪里获得1?请尝试将
“退出”
更改为
“退出”
?另请参见@cnicutar的答案!我使用telnet测试服务器可能是一个错误吗?您没有实现任何类型的协议,因此您没有“消息”的概念。在获得“消息”之前,您必须定义消息的绑定方式,然后必须在代码中实现。(TCP是字节流服务,没有“消息”的概念。)