I'm getting this error while initializing a string in a class
Error : publicclass.cpp:13:6: error: array type 'char [50]' is not assignable sn = "Randomstring";
But char is working. Only getting error with strings
#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;
}
Compiler version is g++ 8.0.0 (getting same error with clang++ ,turboc++(in windows))
Arrays are not assignable.
You can initialise the member when you initialise the object that contains it:
student s{1, "Randomstring"};
You can copy the elements of an existing array after initialisation:
std::strncpy(s.n, "Randomstring", std::size(s.n));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.