【问题标题】:How do I take a mixture of string literals and floats and concatenate them into one string in C?如何混合使用字符串文字和浮点数并将它们连接成 C 中的一个字符串?
【发布时间】:2015-06-25 18:00:09
【问题描述】:

我对 C 有点生疏,我想将几​​个字符串和浮点数连接在一起。特别是,我想制作字符串“AbC”,其中 A 和 C 是字符串文字,b 是浮点数。我知道我必须将浮点数转换为字符串,但我的代码没有编译。下面是我的代码,后面是 gcc 的输出。有关如何修复我的代码的任何建议?

我的程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
double b = 0.5;
char mystring[16];
strcpy(mystring,"A");
strcat(mystring,ftoa(b));
strcat(mystring,"C");
printf("%s",mystring);
return 0;
}

GCC 输出:

test2.c: In function ‘main’:
test2.c:11:1: warning: passing argument 2 of ‘strcat’ makes pointer from integer without a cast [enabled by default]
 strcat(mystring,ftoa(b));
 ^
In file included from test2.c:3:0:
/usr/include/string.h:137:14: note: expected ‘const char * __restrict__’ but argument is of type ‘int’
 extern char *strcat (char *__restrict __dest, const char *__restrict __src)
              ^
/tmp/cc77EVEN.o: In function `main':
test2.c:(.text+0x42): undefined reference to `ftoa'
collect2: error: ld returned 1 exit status

【问题讨论】:

    标签: c strcat


    【解决方案1】:

    你要找的是snprintf

    snprintf(mystring, sizeof mystring, "A%.1fC", b);
    

    【讨论】:

      【解决方案2】:

      您可以将所有行替换为:

      sprintf(mystring, "A%gC", b);
      

      为了安全起见(防止覆盖超出数组末尾):

      snprintf(mystring, sizeof(mystring), "A%gC", b);
      

      【讨论】:

      • 我只是在上面评论说你应该把这个作为答案。然后你做了,你的评论消失了。 :-)
      • @donjuedo 我没有发表那条评论。
      • 哦,哎呀。它几乎和你的一样,但使用了我从未听说过的asprintf()。反正很有趣。
      • 你应该推荐使用snprintf,而不是sprintfsprintf 无法知道有多少可用空间。
      • @donjuedo 这是我的评论;我删除了它,因为asprintf 不像我想的那样工作。
      【解决方案3】:

      C 标准库中没有ftoa 函数。

      仅考虑标准 C 的功能,最简单的方法是使用 snprintf

      #include <stdio.h>
      int main(void)
      {
          double b = 0.5;
          char mystring[16];
          snprintf(mystring, 16, "A%gC", b);
          puts(mystring);
          return 0;
      }
      

      如果您的 C 库具有非标准函数 asprintf,您就不必计算缓冲区的大小:

      #include <stdio.h>
      #include <stdlib.h>
      int main(void)
      {
          double b = 0.5;
          char *mystring = 0;
          if (asprintf(&mystring, "A%gC", b) == -1)
          {
              perror("asprintf");
              return 1;
          }
          puts(mystring);
          free(mystring);
          return 0;
      }
      

      【讨论】:

      • If your C library has the nonstandard function asprintf, that frees you from having to figure out how big to make the buffer 以移植到不提供该功能的环境为代价,如果它对 OP 很重要。
      • 考虑到mysstring 是一个数组,最好在snprintf() 中使用sizeof mystring
      • @EricJ。这就是为什么我说它是“非标准的”。
      • @BlueMoon 我从来不喜欢将sizeof 应用于数组,因为这样的代码很容易被复制并粘贴到数组类型已经衰减的上下文中,现在它是错误的。在生产代码中,我会在两个地方都使用#define MYSTRING_SIZE
      • @zwol:我只是强调失去可移植性的重要性,并不是每个开发人员都清楚它的潜在重要性。
      猜你喜欢
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      • 2015-05-02
      • 2016-01-25
      • 1970-01-01
      • 2022-12-17
      • 2012-02-02
      • 1970-01-01
      相关资源
      最近更新 更多