C++ 如何将一些字符放入先前分配的字符串对象中?
为什么我不能为作为结构的一部分分配的字符串对象变量strcpy一些字符C++ 如何将一些字符放入先前分配的字符串对象中?,c++,C++,为什么我不能为作为结构的一部分分配的字符串对象变量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
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:string并将其与strcpy的手册页进行比较呢?std::string不是纯字符数组,它们不能直接用作strncpy的目标
至于您的代码,您可以简单地将字符串文本分配给现有的字符串对象,例如person对象的数据成员。该字符串将基于文本创建一个内部副本。比如说,
person pupil;
pupil.firstname = "Test";
std::cout << pupil.firstname << std::endl; // prints "Test"
因为strcpy与C样式的字符串和字符缓冲区一起工作,而std::string不是C样式的字符串
您只需执行以下操作:
pupil->firstname = temp;
或者,完全避免温度:
pupil->firstname = "Test";
更好的是,让您的人员的构造函数实际构造一个完整形式的对象:
struct person
{
person ()
:
firstname ("Test")
{
}
string firstname;
string lastname;
int age;
char grade;
};
int main()
{
person * pupil = new person;
}
错误消息是什么?因为std::string不是简单的C样式字符串,它是一个类。使用赋值来复制。您可能会忘记您曾听说过Strucy和类似的函数,而学习如何使用C++字符串。
struct person
{
person ()
:
firstname ("Test")
{
}
string firstname;
string lastname;
int age;
char grade;
};
int main()
{
person * pupil = new person;
}