Error while copying the value of string type variable to a character type variable. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Error while copying the value of string type variable to a character type variable.

Here is the code string cd; char ch[30]; fstream fl("a.txt", ios::in|ios::out); while(getline(fl,cd)){ cout<<cd<<endl; strcpy(ch, cd); /*error over here*/ } I am trying to fetch data from a file and I am displaying it and at the same time I want to copy the value of string cd into char ch[30] but it's showing error. Can anyone plz help me out in how to copy the value of string cd into char ch[30] in c++.

18th Dec 2018, 2:07 PM
S O U ✌️ I K
S O U ✌️ I K - avatar
4 Answers
+ 2
function strcpy expect second parameter of type " char const* " and you passed a "std::string" type. so you should do something like that: strcpy(ch, cd.data());
18th Dec 2018, 3:21 PM
MO ELomari
+ 11
.data() function converts the string into char array (C-style string)
18th Dec 2018, 7:23 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 1
Mohamed ELomari thanx for the answer . Since i am a beginner in c++ can you plz be elaborate about "cd.data()"?
18th Dec 2018, 3:39 PM
S O U ✌️ I K
S O U ✌️ I K - avatar