如何将一些字符放入先前分配的字符串对象中

How do I put some chars into a string object allocated previously?

本文关键字:分配 字符串 对象 字符      更新时间:2023-10-16

为什么我不能strcpy一些字符到一个"字符串"对象变量分配作为结构的一部分?

struct person
{
    string firstname;
    string lastname;
    int age;
    char grade;
};
int main()
{
    person * pupil = new person;
    char temp[] = "Test";
    strcpy(pupil->firstname, temp); // THIS IS INVALID, WHY?
    return 0;
}

std::strings不是普通字符数组,因此它们不能直接用作strncpy的目标。

对于您的代码,您可以简单地将字符串文字分配给现有的string对象,例如person对象的数据成员。该字符串将基于文本创建一个内部副本。例如,

person pupil;
pupil.firstname = "Test";
std::cout << pupil.firstname << std::endl; // prints "Test"

注意,不需要动态地分配person对象。也不需要临时的char数组。

注意,在你的例子中,你也可以用大括号括起来的初始化列表来初始化成员:

person pupil = { "John", "Doe", 42, 'F' };

因为pupil->firstname不是字符指针

为什么不阅读std:string并将其与strcpy

的手册页进行比较呢?

因为strcpy与c风格字符串(字符缓冲区)一起工作,而std::string不是c风格字符串

您可以简单地这样做:

pupil->firstname = temp;

或者,完全避免temp:

pupil->firstname = "Test";

更好的是,让person的构造函数实际构造一个完全形成的对象:

struct person
{
    person ()
    : 
      firstname ("Test")
    {
    }
    string firstname;
    string lastname;
    int age;
    char grade;
};
int main()
{
    person * pupil = new person;
}