C++ 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

本文标题:C++ strcpy:字符串赋值函数

本文地址:https://www.hosteonscn.com/3704.html

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注