QString() vs sprintf()

1k Views Asked by At

I have some code where in, there is a TCP connection between the client and the server. I need to send some xml data to the server and receive a response from it. I am trying to do it like this:

char request[MAX];
sprintf(request, "<attestationRequest><majorVersion>%d</majorVersion><minorVersion>%d</minorVersion></attestationRequest>", major, minor);
write(sockfd,request, length);

while(recv(sockfd, response, MAX, 0) >= 0)
{
    cout << "response " << response;
    //do something;
}   

But the data received is (expected response + request).

If I try to fill the data using QString, the data received is proper.

QString request = QString("<attestationRequest>"
                               "<majorVersion>%1</majorVersion>"
                               "<minorVersion>%2</minorVersion>"
                           "</attestationRequest>")
                            .arg(major)
                            .arg(minor)

The rest of the code is same for both the cases. I receive more than 11000 bytes of data when I use sprintf, but 9000 bytes in case of QString. I am not able to understand if I am missing something.

2

There are 2 best solutions below

0
On

Most likely your problem is, that UTF-16 data is sent through the connection (that is QString.)

Maybe if you tried the w_char-versions of those commands, it might succeed.

1
On

IMO both solution are bad.
It is safer and better to use QXmlStreamWriter. Manual manipulation on text will in most cases end with incorrect encoding or missing escape sequence or other xml format violation.

Other problem is that you didn't gave any data how you perform communication. It is highly probable that there is an error causing your problem.