通常你可以像这样在C中打印一个字符串.
printf("No record with name %s found\n", inputString);
Run Code Online (Sandbox Code Playgroud)
但我想用它制作一个字符串,我该怎么做呢?我在寻找像这样的东西..
char *str = ("No record with name %s found\n", inputString);
Run Code Online (Sandbox Code Playgroud)
我希望很清楚我在寻找什么......
Jam*_*lis 30
一种选择是使用sprintf,它的作用就像printf它的第一个参数一样,指向缓冲区,它应该将结果字符串放入其中.
最好使用snprintf,它采用包含缓冲区长度的附加参数来防止缓冲区溢出.例如:
char buffer[1024];
snprintf(buffer, 1024, "No record with name %s found\n", inputString);
Run Code Online (Sandbox Code Playgroud)
Ben*_*ack 10
你正在寻找sprintf功能家族.他们的一般格式是:
char output[80];
sprintf(output, "No record with name %s found\n", inputString);
Run Code Online (Sandbox Code Playgroud)
但是,sprintf它本身是非常危险的.它容易出现称为缓冲区溢出的问题.这意味着sprintf不知道output你提供的字符串有多大,所以它会愿意为它写入比可用数据更多的数据.例如,这将干净地编译,但会覆盖有效的内存 - 并且没有办法让它sprintf知道它做错了什么:
char output[10];
sprintf(output, "%s", "This string is too long");
Run Code Online (Sandbox Code Playgroud)
解决方案是使用函数as snprintf,它接受一个length参数:
char output[10];
snprintf(output, sizeof output, "%s", "This string is too long, but will be truncated");
Run Code Online (Sandbox Code Playgroud)
或者,如果您使用的是Windows系统,则可以使用_sntprintf变体和朋友,以防止输入或输出字符串溢出.