C++ snprintf"无法传递非POD类型的对象"

use*_*969 2 c++ printf

我正在尝试编写一个具有配置和密钥文件的程序.配置文件读取输入密钥文件的内容,根据需要解析并执行密钥值.

我收到一个错误:警告:无法通过'...'传递非POD类型'struct std :: string'的对象; call将在运行时中止.

我收到此行的错误:

snprintf(command, 256, "tar -xvzf %s %s", destination, source);
system(command);
Run Code Online (Sandbox Code Playgroud)

更多的代码尝试并更好地解释:

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);
Run Code Online (Sandbox Code Playgroud)

关于我做错了什么,或者我应该在哪里寻找的任何建议?

谢谢!

jua*_*nza 11

snprintf什么都不知道std::string.在这种情况下,它期望以null结尾的C字符串,即指向以char空字符结尾的字符序列的开头的指针.您可以std::string通过其c_str()方法获取对象持有的基础空终止字符串:

snprintf(command, 256, "tar -xvzf %s %s", destination.c_str(), source.c_str());
Run Code Online (Sandbox Code Playgroud)


Nem*_*ric 5

使用c_str()成员函数.

snprintf(command, 256, "tar -xvzf %s %s", destination.c_str(), source.c_str());
Run Code Online (Sandbox Code Playgroud)

这将返回一个指向数组的指针,该数组包含一个表示字符串对象当前值的C字符串.