C++ 如何在c++;(g+;+;)

C++ 如何在c++;(g+;+;),c++,C++,初始化类中的字符串时出现此错误 错误: publicclass.cpp:13:6:错误:数组类型“char[50]”不可赋值 s、 n=“随机字符串” 但是char正在工作。仅获取字符串错误 #include<iostream> using namespace std; class student { public: int ht; char n[50]; }; int main() { student s; s.ht = 1; s.n = "Randoms

初始化类中的字符串时出现此错误

错误: publicclass.cpp:13:6:错误:数组类型“char[50]”不可赋值 s、 n=“随机字符串”

但是char正在工作。仅获取字符串错误

#include<iostream>
using namespace std;
class student
{
  public:
  int ht;
  char n[50];
};

int main()
{
  student s;
  s.ht = 1;
  s.n = "Randomstring";
  cout<<"Hallticket no : "<<s.ht<<"\n";
  cout<<"Name : "<<s.n<<"\n";
  return 0;
}
#包括
使用名称空间std;
班级学生
{
公众:
int-ht;
charn[50];
};
int main()
{
学生证;
s、 ht=1;
s、 n=“随机字符串”;

cout数组是不可分配的

初始化包含该成员的对象时,可以初始化该成员:

student s{1, "Randomstring"};
初始化后,可以复制现有数组的元素:

std::strncpy(s.n, "Randomstring", std::size(s.n));

改为使用
std::string
。如果确实需要使用char[]而不是std::string,则需要在其中输入一个值(如果存在任何风险,源字符串大于目标缓冲区或snprintf等,则使用strncpy)。您不能只使用equals。!