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

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

本文关键字:of non-POD objects type pass snprintf cannot C++      更新时间:2023-10-16

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

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

我收到此行的错误:

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

尝试和更好地解释更多代码:

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);

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

谢谢!

snprintfstd::string一无所知。在这种情况下,它需要以 null 结尾的 C 字符串,即指向char的指针,这些指针是以 null 字符结尾的字符序列的开头。可以通过其 c_str() 方法获取由 std::string 对象持有的基础 null 终止字符串:

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

使用c_str()成员函数。

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

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

加油!我们身处21世纪,回到浪潮之巅:

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