2

I know there's a lot information and threads about char array to string conversion, but I tried a lot of "solutions" without any success. I tried this solution which is the closest to my issue but didn't work either.

I have the following code:

recvlen = recvfrom(s, recvbuf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen); if (recvlen < 0) { printf("socket() failed with error code : %d", WSAGetLastError()); } string msgrcv(recvbuf, recvlen); printf("String : %s \n", msgrcv); //Prints the weird characters printf("Array : %s \n", recvbuf); //Prints ok the result 

Any ideas what I'm missing or is wrong?

7
  • @joe Please add your output. Commented Jul 17, 2017 at 11:14
  • In that case -> printf can't handle the C++ string. Commented Jul 17, 2017 at 11:15
  • it's c++, I've got "using namespace std;" on the top of the code, the code compiles and works. Commented Jul 17, 2017 at 11:16
  • 3
    Should be printf("String : %s \n", msgrcv.c_str()) as %s expects a pointer to char array, not a std::string object. Commented Jul 17, 2017 at 11:17
  • 2
    @joe Free tip: Gradually injecting C++ code into C code will not result in very good C++ code and so an important step in switching from C to C++ is to unlearn C idioms and conventions. Commented Jul 17, 2017 at 11:28

2 Answers 2

4

Your strange characters being printed are a result of undefined behavior.

printf("String : %s \n", msgrcv); 

The %s format specifier expects a pointer to a nul terminated character array (C-string). You pass a std::string (assuming a nasty using namespace std; somewhere).

To match data type to format specifier, use std::string::c_str:

printf("String : %s \n", msgrcv.c_str()); 
Sign up to request clarification or add additional context in comments.

Comments

2

The printf format specifier %s requires that the argument must be a pointer (char*) to a null-terminated character array. You didn't pass a char*, but a string.

If string happens to be std::string, then you can get a pointer to the null terminated character string using the c_str member function. Or you could use a stream:

std::cout << "String : " << msgrcv << '\n'; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.