void SetString(char s1[], char s2[]){
str1= s1[];
str2= s2[];
}
private:
char str1[20];
char str2[20];
What's wrong in that code please some one tell me.
Its giving me following error:
stringhandler.cpp: In member function ‘void StringHandler::SetString(char*, char*)’:
stringhandler.cpp:25: error: expected primary-expression before ‘]’ token stringhandler.cpp:26: error: expected primary-expression before ‘]’ token
enter image description here
You can't copy C-strings like that, s1 and s2 both decay to a pointer and you have to use strcpy to copy them:
strcpy(str1, s1);
strcpy(str2, s2);
But you're working with C++ so really you should be using std::string:
void SetString(const std::string& s1, const std::string& s2)
{
str1= s1;
str2= s2;
}
private:
std::string str1;
std::string str2;
or, for C++11 and higher:
void SetString(std::string s1, std::string s2)
{
str1= std::move(s1);
str2= std::move(s2);
}
This solves a lot of problems that come with C-strings for you.
You can not do str1=s1[]. It is not valid. Use this instead to copy an array to another:
void SetString(char s1[], char s2[]){
std::copy(s1, s1+20, std::begin(str1));
std::copy(s2, s2+20, std::begin(str2));
}
Even better, use std::array instead (if your case is general) or std::string if you are dealing with strings as array of char. Something like this:
void SetString(const std::array<char,20>& s1, const std::array<char,20>& s2){
str1=s1;
str2=s2;
}
private:
std::array<char,20> str1;
std::array<char,20> str2;
or:
void SetString(const std::string& s1, const string& s2){
str1=s1;
str2=s2;
}
private:
std::string str1;
std::string str2;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With