C语言—strncat()

作者:追风剑情 发布于:2019-10-28 21:28 分类:C

strncat()函数可以利用第三个参数指定要将第二个参数的字符数拼接到第一个参数。

示例

  1. //Visual Studio中加上这句才可以使用scanf()
  2. //否则只能使用scanf_s()
  3. #define _CRT_SECURE_NO_WARNINGS
  4. #include <stdio.h>
  5. #include <stdbool.h>
  6. //引入字符串函数string.h
  7. //一些ANSI之前的系统使用strings.h头文件,而
  8. //有些系统可能根本没有字符串头文件。
  9. #include <string.h>
  10.  
  11. #define SIZE 30
  12. #define BUGSIZE 13
  13.  
  14. char * s_gets(char * st, int n);
  15.  
  16. //argc: 参数个数 argv[]: 参数数组
  17. int main(int argc, char *argv[])
  18. {
  19. char flower[SIZE];
  20. char addon[] = "s smell like old shoes.";
  21. char bug[BUGSIZE];
  22. int available;
  23.  
  24. puts("What is your favorite flower?");
  25. s_gets(flower, SIZE);
  26. if ((strlen(addon) + strlen(flower) + 1) <= SIZE)
  27. strcat(flower, addon);//没第三个参数
  28. puts(flower);
  29. puts("What is your favorite bug?");
  30. s_gets(bug, BUGSIZE);
  31. available = BUGSIZE - strlen(bug) - 1;
  32. //利用第三个参数避免缓冲区溢出
  33. strncat(bug, addon, available);
  34. puts(bug);
  35.  
  36. system("pause");
  37. return 0;
  38. }
  39.  
  40. char * s_gets(char * st, int n)
  41. {
  42. char * ret_val;
  43. int i = 0;
  44. ret_val = fgets(st, n, stdin);
  45. if (ret_val) //即,ret_val != NULL
  46. {
  47. while (st[i] != '\n' && st[i] != '\0')
  48. i++;
  49. if (st[i] == '\n')
  50. st[i] = '\0';
  51. else
  52. while (getchar() != '\n')
  53. continue;
  54. }
  55. return ret_val;
  56. }

运行测试

1111.png

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号