【问题标题】:How to store output of two printf into a variable in c [duplicate]如何将两个printf的输出存储到c中的变量中[重复]
【发布时间】: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


【解决方案1】:

到目前为止,您每次都用最新的snprintf 调用覆盖缓冲区。

您需要考虑snprintf 返回的最后写入字节数。

示例:

int numBytes = 0;

for (c = 1; c <= 10; c++)
{
    numBytes += snprintf(buffer+numBytes, sizeof(buffer)-numBytes, "%d", c+2);
    if (c%2) {
        numBytes += snprintf(buffer+numBytes, sizeof(buffer)-numBets, "%d", c+2);
    }    
}

【讨论】:

  • 谢谢,这是使用虚拟代码,但是当我与实际代码集成时,我得到了Bus error,就像来自 strace write(1, "\n", 1 ) = 1 --- SIGBUS {si_signo=SIGBUS, si_code=SI_KERNEL, si_addr=0} --- +++ killed by SIGBUS +++ Bus error 的输出一样
  • 在这一行numBytes += snprintf(buffer + numBytes, sizeof(buffps) -numBytes, "\n");
  • buffpsbuffer 的关系是什么?更重要的是,此时您的buffer 有多大,numBytes 的价值是多少。鉴于那行代码多么简单,我能看到的唯一解释是buffer + numBytes 不指向内存的可写区域。您是否会超出缓冲区,而 snprintf 允许它,因为 sizeof(buffps)sizeof(buffer) 不同?
  • @monk 你能用新问题更新你的问题吗?
  • @kiranBiradar ,您的回答正确回答了原始问题。我会调试我最好的,如果需要我会提出另一个问题。
猜你喜欢
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 2015-09-26
  • 1970-01-01
  • 2019-11-05
  • 1970-01-01
  • 2017-06-13
  • 1970-01-01
相关资源
最近更新 更多