c - 使用 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”
解决方案
推荐阅读
- python - 在微调 Layoutlm 时过度拟合小数据集。建议使用哪些正则化技术?
- json - 添加外部帐户作为 S3 对象的 ACL
- python - StyleFrame row_index AttributeError:“int”对象没有属性“value”
- java - 如何在firestore中使用给定的语句
- nfs - GnuCobol 编译器 COBC 不能与 NFS 挂载磁盘的 -I 选项一起正常工作
- python - 从 Pandas 数据帧到 Spark 数据帧的转换需要大量时间
- c# - 如何从 api 获取单个对象并显示它
- java - JAVA_HOME 未设置,在您的 PATH (Android Studio) 中找不到“java”命令
- javascript - 为什么我的文本框不接受小数点?
- javascript - Discord.js 'awaitReactions 不是函数' 错误