C ++使用Winsock2缓冲区将Char *转换为Int时出错

时间:2018-02-05 16:29:00

标签: c++ sockets buffer winsock2

我一直在寻找理解我如何转换的时间

a(char * to int)我在尝试读取缓冲区时到达valread = socket( sock , buffer, 1024);

我一直在寻找任何方法来正确转换它,但我不能。谢谢你的帮助,这是我的代码:)

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include<winsock2.h>
#include <Windows.h>
#include<WS2tcpip.h>
#include <string.h>
#define PORT 8080

int main(int argc, char const *argv[])
{
    struct sockaddr_in address;
    int sock = 0, valread;
    struct sockaddr_in serv_addr;



    char const *hello = "Hello from client";
    char buffer[1024] = {0};
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("\n Socket creation error \n");
        return -1;
    }

    memset(&serv_addr, '0', sizeof(serv_addr));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);

    // Convert IPv4 and IPv6 addresses from text to binary form
    if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0) 
    {
        printf("\nInvalid address/ Address not supported \n");
        return -1;
    }

    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    {
        printf("\nConnection Failed \n");
        return -1;
    }
    send(sock , hello , strlen(hello) , 0 );
    printf("Hello message sent\n");
    valread = socket( sock , buffer, 1024);
    printf("%s\n",buffer );
    return 0;
}

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你想将char *转换为int?

要在c ++中将char *转换为int,通常有几种方法,主要取决于您可以使用的c ++标准。以下代码片段假设您所需的char *名为m_pChar

来自标题stdlib.h的

std :: atoi(数组到整数)

int i;
i = std::atoi(m_pChar);