【发布时间】:2019-10-07 01:12:00
【问题描述】:
如何将多个命令或代码块的输出存储到单个变量中。我需要将它写入一个变量,以便它可以在多个地方使用。
以下是一个包含代码块的虚拟程序(见注释),其中有 两个 printf 语句,我需要将它们存储到一个变量中以便以后使用。
显示输出格式的示例代码
#include <stdio.h>
int main()
{
int c;
// code block start here
char buffer[128];
for (c = 1; c <= 10; c++)
{
printf("%d",c+2);
if(c%2){
printf("%d\n",c+2);
}
}
//code block ends here
// store the whole output of above code block into variable
//send the data on socket ---this is working ,but need the whole data into the variable
return 0;
}
上面的程序结果是这样的
-->./a.out
33
455
677
899
101111
12
我尝试使用snprintf将两个printf的输出存储到一个名为buffer的变量中,但是它覆盖了最后一个printf的数据。
#include <stdio.h>
int main()
{
int c;
// code block start here
char buffer[128];
for (c = 1; c <= 10; c++)
{
// printf("%d",c+2);
snprintf(buffer, sizeof(buffer), "%d", c+2);
if(c%2){
// printf("%d\n",c+2);
snprintf(buffer, sizeof(buffer), "%d", c+2);
}
}
printf("buffer is %s\n",buffer);
//code block ends here
// store the whole output of above code block into variable
//send the data on socket ---this is working ,but need the whole data into the variable
return 0;
}
当前输出:
buffer is 12
期望的输出:
buffer is 33\n455\n677\n899\n101111\n12
【问题讨论】:
-
snprintf返回什么?当可能遇到附录snprintf时,这可能很有用,特别是关于目标缓冲区的偏移。
标签: c