user2630969
user2630969

Reputation: 57

C++ snprintf "cannot pass objects of non-POD type"

I am trying to write a program that has a config and key file. The config file reads what ever is inputted into the key file, parses and executes the key values as needed.

I am getting an error: warning: cannot pass objects of non-POD type ‘struct std::string’ through ‘...’; call will abort at runtime.

I am receiving the error on this line:

snprintf(command, 256, "tar -xvzf %s %s", destination, source);
system(command);

More of the code to try and better explain:

std::string source = cfg.getValueOfKey<std::string>("source");
std::string destination = cfg.getValueOfKey<std::string>("destination");
int duration = cfg.getValueOfKey<int>("duration");
int count, placeHolder, placeHolderAdvanced;
count = 1;
char command[256];

snprintf(command, 256, "tar -xvzf %s %s", destination, source);
system(command);

//Creates folder 1.
snprintf(command, 256, "mkdir %i", count);
system(command);

//Removes the last folder in the group.
snprintf(command, 256, "rm -rf %i", duration);
system(command);

Any suggestions on what I am doing wrong, or where I should be looking?

Thank you!

Upvotes: 2

Views: 6781

Answers (3)

Jean Davy
Jean Davy

Reputation: 2240

Come on ! We are in the 21 century, go back to the top of the wave:

#include <sstream>
...
stringstream command;
command << "tar -xvzf " << destination << " " << source;

Upvotes: 1

Nemanja Boric
Nemanja Boric

Reputation: 22177

Use c_str() member function.

snprintf(command, 256, "tar -xvzf %s %s", destination.c_str(), source.c_str());

This will return a pointer to an array that contains a C-string representing the current value of the string object.

Upvotes: 5

juanchopanza
juanchopanza

Reputation: 227468

snprintf knows nothing about std::string. In this case, it expects null-terminated C strings, that is, pointers to char which are the beginning of a sequence of characters that ends in a null character. You can obtain the underlying null terminated string held by a std::string object via its c_str() method:

snprintf(command, 256, "tar -xvzf %s %s", destination.c_str(), source.c_str());

Upvotes: 11

Related Questions