中断长代码 snprintf 格式和参数



我想用 += 在同一个变量上拆分参数?

int QueryExecute = snprintf(UpdateQuery, sizeof(UpdateQuery),"One=%u, Two=%d,",One, Two);

我可以这样做吗?

int QueryExecute = snprintf(UpdateQuery, sizeof(UpdateQuery),"One=%u, Two=%d,");
int QueryExecute += One, Two;

基本上,我想将格式和参数拆分为不同的变量。

对不起,英语不好

我可以这样做吗?

不,你不能。但是你可以拆分行,C++通常不关心空格:

int QueryExecute = snprintf(UpdateQuery, sizeof(UpdateQuery), "One=%u, Two=%d,",
One, Two);

如果这不是您关心的线宽,并且希望稍后提供以下参数(OneTwo(,则可以使用std::bind执行此操作:

using namespace std::placeholders;
auto snprintf_later = std::bind(snprintf, UpdateQuery, sizeof(UpdateQuery), "One=%u, Two=%d,", _1, _2);
// ...
int QueryExecute = snprintf_later(One, Two);

如果你不需要那么具体地说明你把字符串放在哪里;我建议使用字符串流,因为它消除了您担心一和二类型的需要;以及将变量放在它们将被放入流中的位置:

#include <sstream>

然后用法:

std::stringstream data;
data << "One=" << one
<< "Two=" << two;
std::string buffer = data.str();

最新更新