之前的一个问题显示了打印到字符串的好方法.答案涉及va_copy:
std::string format (const char *fmt, ...);
{
va_list ap;
va_start (ap, fmt);
std::string buf = vformat (fmt, ap);
va_end (ap);
return buf;
}
std::string vformat (const char *fmt, va_list ap)
{
// Allocate a buffer on the stack that's big enough for us almost
// all the time.
s ize_t size = 1024;
char buf[size];
// Try to vsnprintf into our buffer.
va_list apcopy;
va_copy (apcopy, ap);
int needed = vsnprintf (&buf[0], size, fmt, ap);
if (needed <= …
Run Code Online (Sandbox Code Playgroud) 有没有人知道将printf样式函数的输出重定向到字符串的安全方法?显而易见的方法导致缓冲区溢出.
就像是:
string s;
output.beginRedirect( s ); // redirect output to s
... output.print( "%s%d", foo, bar );
output.endRedirect();
Run Code Online (Sandbox Code Playgroud)
我认为问题与询问一样,"会产生多少个字符?" 想法?
在 Python 中,可以使用 f-strings 方便地格式化字符串:
a = 42
print(f"a = {a}") # prints "a = 42"
Run Code Online (Sandbox Code Playgroud)
是否可以在编译时在 C++ 中做这样的事情,或者是format("a = {}", a);
最接近 f-strings 的东西?
编辑:我并不是说这些格式化方法应该在运行时工作。编译器不能只在编译时通过名称查找当前作用域中可见的变量吗?就像,如果它遇到字符串,f"foo = {foo}"
它可以将此字符串替换为std::format("foo = {}", foo)
代码
我尝试过以下程序将值导出到环境变量.我想将一个整数值导出到环境变量.程序下面的值是"a"而不是1.如何将整数值导出到该环境变量.
#include<stdio.h>
void chnge_env_var(int a)
{
char *name1="ENV_VAR";
char *val=NULL;
int status;
status = putenv("ENV_VAR=a");
printf("status %d\n",status);
val = getenv(name1);
printf("val %s\n",val);
}
int main()
{
int a=1;
chnge_env_var(a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)