gpt4 book ai didi

c - C语言中反转字符串的TCP程序给出一半的结果

转载 作者:可可西里 更新时间:2023-11-01 02:55:33 25 4
gpt4 key购买 nike

我已经编写了一个 TCP 客户端/服务器程序来反转字符串,但是结果部分正确。

客户:

#‎include‬<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<sys/types.h>
void main()
{
struct sockaddr_in server;
int sock;
char buffer[20];

printf("Enter a string :");
scanf("%s",buffer);

server.sin_family = AF_INET;
server.sin_port = 2000;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
sock = socket(AF_INET,SOCK_STREAM, 0);

connect(sock, (struct sockaddr*) &server, sizeof(server));
send(sock, buffer, sizeof(buffer), 0);
recv(sock, buffer, sizeof(buffer), 0);

printf("The reverse string is: %s",buffer);
printf("\n");
}

服务器:

‪#‎include‬<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<string.h>
void main()
{
struct sockaddr_in server, client;
char buffer[20], temp;
int n, sock, newsock, i, j;

sock = socket(AF_INET, SOCK_STREAM, 0);
server.sin_family = AF_INET;
server.sin_port = 2000;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
bind(sock, (struct sockaddr*) &server, sizeof(server));

listen(sock, 2);
n = sizeof(client);
new sock = accept(sock, (struct sockaddr*) &client, &n);
for(;;)
{
recv(newsock, buffer, sizeof(buffer), 0);
i = 0;
j = strlen(buffer) - 1;
while(i<j)
{
temp = buffer[i];
buffer[i] = buffer[j];
buffer[j] = temp;
i++;
j--;
}
send(newsock, buffer, sizeof(buffer), 0);
}
}

现在当我运行它并假设我输入的字符串是“hello how are you”但结果只是“olleh”并且跳过了句子的其余部分。我在这里遗漏了什么吗?

最佳答案

您的问题很早就开始了,在 scanf 函数中,因为 %s 一直读取到第一个空格(就在“hello”之后)。您需要阅读到行尾(getline 可以为您完成)。

关于c - C语言中反转字符串的TCP程序给出一半的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35007921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com