Search code examples
c++sendto

C++ - Using sendto() with a basic string


My current code doesn't work I can't find a way to send the string with sendto() or convert the basic string to a char* so that it works. Thanks. Here is my current code:

for (vector<string>::iterator it=lines.begin(); it!=lines.end(); ++it){
    if (int bytes = sendto(sockfd, *it, strlen(*it), 0, (struct sockaddr*)&server, svrlen) == -1){
        printf("Send error.");
        exit(1);
    }
}

Solution

  • Use the size() or length() members to get the length of a string, and data() to get a pointer to the data:

    sendto(sockfd, it->data(), it->size(), ...);
    

    If you're stuck with a pre-2011 implementation, then data() won't exist, so use c_str() instead.