Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ non-POD warning for passing a string?

void displayinfo(string &filename)
{
printf("%s% 38s\n", "Filename:", filename);
...

Warning: A non-POD object of type "std::string " passed as a variable argument to function "std::printf(const char*, ...)".

There is nothing online explaining what that warning means.

How would I get the printf to write this (assuming filename = test.txt):

Filename: (right justify filename) test.txt

Thanks in advance.

like image 685
user2369405 Avatar asked Jun 09 '13 11:06

user2369405


2 Answers

The explanation is quite simple: only PODs (Plain Old Data structures) can be passed as an argument to a variadic function (not a variadic function template though, just a simple variadic function using the ellipses).

std::string is not a POD, but you can do:

printf("%s% 38s\n", "Filename:", filename.c_str());
//                                       ^^^^^^^^

The c_str() member function returns a const char* to the encapsulated C string.

like image 135
Andy Prowl Avatar answered Nov 02 '22 18:11

Andy Prowl


printf, when used with the %s format specifier, requires a pointer to char. You can get that from an std::string via the c_str() method:

printf("%s% 38s\n", "Filename:", filename.c_str());

As an aside, note that if you don't intend to modify or copy the input string, you should pass by const reference:

void displayinfo(const string& filename) { .... }
like image 23
juanchopanza Avatar answered Nov 02 '22 19:11

juanchopanza