You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用std::cin.getline()导致Socket连接终止的问题排查

井字棋Socket客户端:cin.getline()导致循环终止与连接关闭问题

我基于微软官方Socket客户端代码开发了一款通过Socket与服务器通信的井字棋游戏,但调用std::cin.getline()时,while循环会直接停止,同时Socket连接也被关闭,找不到问题根源。

代码片段

const char *sendbuf = "NEWG";
// comment this when testing cin.
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;

// Receive until the peer closes the connection
//  we need to communicate to the server 

printf(" | | | \    / _  |  _  _  ._ _   _  | | |\n");
printf(" o o o  \/\/ (/_ | (_ (_) | | | (/_ o o o\n");
char *usrin;
std::cout << "Welcome to the tictactoe game !!\n";
int x = 1;
while (true) {
    std::cout <<"test";
    //std::cin.getline(sendbuf, strlen(sendbuf));
    // if(sendbuf == 0){
    //     std::cout << "give me sometthign to work with!";
    // } 
    std::cout << "test";
    // Send user input to the server
    int iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
    if (iResult == SOCKET_ERROR) {
        printf("send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    printf("Bytes Sent: %d\n", iResult);

    // Receive and print data from the server
    iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
    if (iResult > 0) {
        printf("Bytes received: %d\n", iResult);
        recvbuf[iResult] = '\0'; // Null-terminate the received data
        printf("Received data: %s\n", recvbuf);
    } else if (iResult == 0) {
        printf("Connection closed\n");
    } else {
        printf("recv failed with error: %d\n", WSAGetLastError());
    }
    
}

// cleanup
closesocket(ConnectSocket);
WSACleanup();

return 0;
}

已尝试的解决方法

  • 将sendbuf的类型从const char*改为char、char*,编译报错
  • 改用std::cin >>替代getline(),问题依旧存在
  • 更换终端测试,无效,确认问题根源在cin相关函数

内容的提问来源于stack exchange,提问作者Fardin Mahid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 01:28:29