比较C中的字符串-strcmp [英] Comparing strings in C - strcmp
问题描述
我在比较C语言中的字符串时遇到了麻烦(我还不太熟悉).我在此服务器应用程序上有套接字,正在等待接受来自客户端的数据.在程序的这一特定部分中,我希望能够基于从客户端接收的数据执行MySQL查询.我希望能够知道何时接收到的数据具有"newuser"值,以启动简单的注册过程. Strcmp返回一个正1值,我相信我应该得到一个0,因为这些值应该相等.
I'm having trouble comparing strings in C (with which I am fairly new to). I have socket on this server application waiting to accept data from a client. In this particular portion of my program I want to be able to execute a MySQL query based on the data received from the client. I want to be able to know when the received data has the value of "newuser" to initiate a simple registration procedure. Strcmp is returning a positive 1 value where I believe I should be getting a 0 because the values should be equal.
源代码:
//setup socket
//loop and select structure to handle multiple connections
if ((nbytes = recv(i, buf, sizeof buf, 0)) <= 0) {
// got error or connection closed by client
if (nbytes == 0) {
// connection closed
printf("selectserver: socket %d hung up\n", i);
} else {
perror("recv");
}
close(i); // bye!
FD_CLR(i, &master); // remove from master set
} else {
char check[] = "newuser";
char fromUser[sizeof check];
strncpy(fromUser,buf, sizeof check);
printf("length of fromUser: %d\n", sizeof fromUser);
printf("length of check: %d\n", sizeof check);
printf("message from user: %s\n", fromUser);
printf("check = %s \n", check);
int diff = strcmp(fromUser, check);
printf("compare fromUser to check: %d\n", diff);
if ( strcmp(fromUser, check) == 0) {
printf("aha! new user");
}
输出:
length of fromUser: 8
length of check: 8
newuser from user: newuser
check = newuser
compare fromUser to check:
我感觉我没有正确处理传入的缓冲区或错误地复制了缓冲区.
I have a feeling I'm not handling the incoming buffer correctly or erroneously copying the buffer.
推荐答案
strncpy
最多复制-在这种情况下-sizeof
个校验字节.如果nul字节不在该范围内,则不会复制该字节.您可能会将"newuser"一词作为一个较长句子的一部分,例如"newuser blah blah",因此您需要自己放置该nul
strncpy
copies at most - in this case - sizeof
check bytes. If the nul byte is not in that range it is not copied. You probably are getting the word "newuser" as part of a longer sentence, like "newuser blah blah" so you need to place that nul yourself
strncpy(fromUser, buf, sizeof check);
fromUser[sizeof check - 1] = '\0';
或使用strlcpy
(如果可用).
这篇关于比较C中的字符串-strcmp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!