简体   繁体   中英

C - Compare a char array with string

I have a socket server which should receive a message and write an answer. For some messages I want to send a special answer. If the message is for example "Hello" I want to answer "Hi!" . Here is a part of my code:

...
char in[2000];
char out[2000];
...
while((read_size = recv(fd, in, 2000, 0)) > 0){

    if(strcmp(in, "Hello") == 0){

        strcpy(out, "Hi!\n");

    }
    else{

        strcpy(out, in);

    }

    write(fd, out, strlen(out));

}
...

But the strcmp() doesn't work fine here. Because when I type in "Hello" there is not only the "Hello" in the in variable, because the length is 2000. But how can I check now, if the received message is "Hello" ?

使用strncmp函数,它比较字符串的前n个字节:

if (strncmp(in, "Hello", strlen("Hello")) == 0) ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM