CPP strcat函数使用

mac2022-06-30  90

strcat函数原型

char * strcat ( char * destination, const char * source );

strcat常见写法

// main.cpp // 字符数组strcat()函数的使用 // char * strcat ( char * destination, const char * source ); // 来源的头文件 #include <string.h> 或者#include <cstring> // 功能:将字符串 source连接到字符串 destination的后面,并把destination地址返回。 // 常见问题:strcat()函数常见的错误就是数组越界,即两个字符串连接后,长度超过第一个字符串数组定义的长度,导致越界 // Created by mac on 2019/4/5. // Copyright © 2019年 mac. All rights reserved. #include <iostream> #include <cstring> using namespace std; int main(int argc, const char * argv[]) { //几种常见的写法: // 写法一:直接不定义字符数组,定义两个字符指针。编译成功,运行出错。 // char *p="Hell"; // char *q="o,World!"; // strcat(p,q); // cout<<p<<endl; // 写法二:定义了字符数组,但是不指定字符数组的长度, 程序的编译运行都没有问题。 // char p[]="Hell"; // char *q="o,World!"; // strcat(p, q); // cout<<p<<endl; //写法三:定义字符数组的时候指定字符数组的大小,程序的编译运行都没有产生问题 // char p[30]="Hell"; // char *q="o,World!"; // strcat(p, q); // cout<<p<<endl; //写法四:定义没有指定长度的字符数组和字符串常量,编译运行都没有问题 // char p[]="Hell"; // strcat(p,"o,World"); // cout<<p<<endl; //写法五:直接连接两个字符串常量 编译成功,运行出错。 //cout<<strcat("Hell", "o,World")<<endl; return 0; }

运行成功输出

运行失败输出

Tips

字符串连接的时候主要看destination中的空间是否充足。

参考文献

https://blog.csdn.net/candyliuxj/article/details/6786718http://www.cplusplus.com/reference/cstring/strcat/

转载于:https://www.cnblogs.com/overlows/p/10658947.html

相关资源:c 实现strcat字符串连接库函数的方法详解
最新回复(0)