C:字符串比较 bool done; 完成=错误; 而(!完成){ /*读留言*/ b0(味精,100); printf(“[client]键入某物:”); fflush(stdout); 读取(0,msg,100); 如果(strcmp(msg,“/done”)==0){ 完成=正确; /*将消息发送到服务器*/ 如果(write(sd,msg,100)
read(2)在字符串末尾包含“\n”。当使用低级读取时,您将获得所有内容。当尝试调试字符串时,在print语句中加引号可能会有所帮助,如C:字符串比较 bool done; 完成=错误; 而(!完成){ /*读留言*/ b0(味精,100); printf(“[client]键入某物:”); fflush(stdout); 读取(0,msg,100); 如果(strcmp(msg,“/done”)==0){ 完成=正确; /*将消息发送到服务器*/ 如果(write(sd,msg,100),c,linux,C,Linux,read(2)在字符串末尾包含“\n”。当使用低级读取时,您将获得所有内容。当尝试调试字符串时,在print语句中加引号可能会有所帮助,如 bool done; done = false; while (!done) { /* read the message */ bzero(msg, 100); printf("[client]Type something: "); fflush(stdout); read(0, msg, 100); if (
bool done;
done = false;
while (!done) {
/* read the message */
bzero(msg, 100);
printf("[client]Type something: ");
fflush(stdout);
read(0, msg, 100);
if (strcmp(msg, "/done") == 0) {
done = true;
/* sending the message to the server */
if (write(sd, msg, 100) <= 0) {
perror("[client]Error sending the message to the server.\n");
return errno;
}
} else {
/* sending the message to the server */
if (write(sd, msg, 100) <= 0) {
perror("[client]Error sending the message to the server.\n");
return errno;
/* reading the answer given by the server*/
if (read(sd, msg, 100) < 0) {
perror("[client]read() error from server.\n");
return errno;
}
/* printing the received message */
printf("[client]The received message is: %s\n", msg);
}
}
因为这会立即显示不可见的空白。当您从0读取时,您是从stdin读取的。如果这是您正在键入的终端(您不说),则可能已将其设置为正常(规范)模式,因此您将读取一行,其中可能包含换行符(\n)字符。因此,当您输入
/done
时,您在msg缓冲区中得到的字符串是“/done\n”
,它与“/done”不匹配
…TCP不是消息协议。它不会将字节粘合到消息中。如果要使用TCP发送和接收消息,则需要实现发送和接收消息的功能
我必须强烈提醒您不要陷入这样的陷阱:将代码从尝试时的“碰巧不工作”更改为尝试时的“碰巧工作”意味着您已经修复了它。如果
read
返回1,您的代码将失败。您需要实现一个合理的函数来接收消息,否则您的代码只会在我很幸运,我可以从痛苦的经历中告诉你,总有一天你的运气会耗尽。当你用调试器逐步检查代码时,你看到了什么?bzero()
被弃用(POSIX)了,并且从来没有被C语言标准指定过。你应该使用memset()
相反。然而,我不认为这是问题的根源。read(0,msg,100);
的返回值是否总是如预期的那样?测试读取的结果将是一个好主意。Adn为什么要使用如此低级别的函数来读取stdin。strcmp(msg,“/done”)
在read(0,msg,100)时是一个问题
读取100个字符,因为msg
不一定是字符串。
printf("[client]The received message is: '%s'\n", msg);