如何将一些字符放入先前分配的字符串对象中
How do I put some chars into a string object allocated previously?
为什么我不能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;
}
相关文章:
- 用字符串的向量分配字符串向量
- 在C++中动态分配字符串数组
- 分配字符串uint8_t
- 如何分配字符串来提升野兽multi_buffer
- 分配字符串时EXCEPTION_ACCESS_VIOLATION
- 使用带有动态分配字符串的strcpy_s()和strcat_s()
- 如何分配字符串文本
- C 循环不重新分配字符串值
- 如何在C 中分配字符串数组
- 动态内存分配 C++ 字符串
- 如何存储可以分配字符串的数值
- 通过引用传递结构并分配字符串
- 动态分配字符串文字
- 分配字符串数组时出现分段错误
- 如何从 Arduino 的 C++ 类中的构造函数中分配字符串字段
- 动态分配 C 字符串内存,无需先询问用户输入时间
- 分配字符串时出现 char* 新建和删除 [] 错误
- C++正在记住指向已分配字符串的指针
- 在结构中分配字符串时出现 Seg 错误
- 指向字符串的指针,可用于动态分配字符串数组