设为首页 加入收藏

TOP

CPP strcat函数使用
2019-04-05 18:07:56 】 浏览:91
Tags:CPP strcat 函数 使用

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中的空间是否充足。

参考文献

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Gym100025K 下一篇小程序大道理(一)引用的用途

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目