strncpy 和 strcat 用法

strncpy and strcat usage

我的作业要求显示我的姓名,如下所示:“姓氏,名字”。姓然后 [逗号 space] 名字。同时不移动该名称后的其余文本。这是我的代码:

  char str1[11];
  char str2[3];
  char str3[16];
  strcpy (str1,fn);
  strcpy (str2,", ");
  strcpy (str3,ln);
  strncat (str1, str2, 14);
  strncat (str1, str3, 31);

我的老师说我做了他想要的,但他不喜欢我用了多少行代码,说我做了超出我需要的额外工作。

变量:ln = last namefn = first name 我为 ', ' 逗号制作了 str2 space。

他要我做什么?

您的 strcpy 调用真的没有必要,因为您已经在变量中有了名字和姓氏。您可以创建一个足够大的缓冲区来容纳整个字符串,然后使用 strcat 创建最终的 "lastname, firstname" 字符串。

这就是您所需要的:

strcpy (str1,ln);    // Copy the last name to str1
strcat (str1,", ");  // Now append ", " to the last name in str1
strcat (str1,fn);    // Lastly, append the first name to str1

您必须确保 str1 足够大以容纳所有这些。 13 个字符的数组可能不够。

char result[50];

strcpy(result, ln);
strcat(result, ", ");
strcat(result, fn);

他是对的,你使用了太多语句(并且浪费了太多内存)。

假设你知道字符串的长度,为什么不呢

char result[50];

sprintf(result,"%s, %s",ln, fn);

我很惊讶你的导师接受了你的回答。您将结果累积到 char 数组 str1 中,您声明它只有 11 个字符。除非 strlen(ln)+strlen(fn)<=8,否则您将溢出为结果 str1 分配的 space。在糟糕的过去,C 程序员会简单地分配一个看起来足够大的结果数组,而不会费心去检查。 stdio.h 中的标准 C 库函数 sprintf 专为这项工作而设计:

#include <stdio.h>
...fn, ln defined...
char result[80];  /* 80 characters is probably enough */
sprintf(result, "%s, %s", ln, fn);

现代 C 程序员永远不会认为 lnfn 足够短,不会溢出结果数组,无论多长。安全、现代的替代方法是将 sprintf 调用替换为 snprintf:

snprintf(result, 80, "%s, %s", ln, fn);

您还可以使用 strcpy/strcat 系列函数,它们位于 string.h 中。 (这是在你的作业中指定的吗?)安全的现代等价物是 strncpystrncat,它们让你指定要复制的最大字符数。使用这些函数的快速、肮脏但安全的解决方案是:

char result[80];
result[0] = '[=12=]';     /* initialize result to "" */
strncat(result, ln, 40);
strcat(result, ", ")  /* you know this adds exactly two characters */
strncat(result, fn, 38);

strncpy 调用是危险的,因为它可能不会在 result 中留下以 null 结尾的字符串,这将导致后续的 strcat 失败。这并不比您所做的少多少行,但是仅使用这些 string.h 函数,很难做得更好,并且无论 lnfn给出。