加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C++ strcpy:字符串赋值函数

发布时间:2020-12-16 07:38:56 所属栏目:百科 来源:网络整理
导读:使用 C++ 字符数组与使用 string 对象不同的第一种方式是,除了在定义时初始化它,不能使用赋值运算符给它赋值。换句话说,不能使用以下方式直接给 name 字符数组赋值: name = "Sebastian";??? // 错误 相反,要为字符数组赋值,必须使用一个名为 strcpy (发
使用 C++ 字符数组与使用 string 对象不同的第一种方式是,除了在定义时初始化它,不能使用赋值运算符给它赋值。换句话说,不能使用以下方式直接给 name 字符数组赋值:

name = "Sebastian";??? // 错误

相反,要为字符数组赋值,必须使用一个名为 strcpy (发音为 string copy)的函数,将一个字符串的内容复制到另一个字符串中。在下面的代码行中,Cstring 是接收值的变量的名称,而 value 则是字符串常数或另一个 C 字符串变量的名称。

strcpy(Cstring,value);

下面的程序显示了 strcpy 函数的工作原理:
// This program uses the strcpy function to copy one C-string to another.
#include <iostream>
using namespace std;

int main()
{
    const int SIZE = 12;
    char name1[SIZE],name2[SIZE];
    strcpy(name1,"Sebastian");
    cout << "name1 now holds the string " << name1 << endl;
    strcpy(name2,name1);
    cout << "name2 now also holds the string " << name2 << endl;
    return 0;
}
程序输出结果:

name1 now holds the string Sebastian
name2 now also holds the string Sebastian

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读