Reputation: 23
I'm converting a string into an array of char.
I've tried static_cast to do this and I'm somewhat new to programming. I'm not sure if I'm using it correctly.
string Password::encrypt(string p_user){
pass = p_user;
char word[pass.length()];
for(int i = 0; i < pass.length(); i++){
word[i] = static_cast<char>(pass.substr(i, i+1)); // Every letter in one index
}
return "";
}
The error is as follows: "Cannot convert 'std::_cx11::basic_string
Upvotes: 0
Views: 116
Reputation: 404
The problem here is that substr
method of std::string
class returns std::string
, that cannot be converted to char through static_cast
. Let me provide a work around for this problem:
char word[pass.length()];
for(int i = 0; i < pass.length(); i++){
word[i] = static_cast<char>(pass.substr(i, i+1)[0]); // Here as it is a length of 1, we can access with index 0, which will give a char
}
Infact there is no need of static_cast
also, you can simply write as follows:
char word[pass.length()];
for(int i = 0; i < pass.length(); i++){
word[i] = pass[i];
}
Hope this helps, thanks,
Rajkumar
Upvotes: 1
Reputation: 206557
There is nothing in the standard library that support casting a std::string
to a char
. Hence, static_cast<char>(pass.substr(i, i+1))
is an invalid expression. It's not clear to me why you are using that instead of the much more straight forward:
word[i] = pass[i];
Use of
char word[pass.length()];
is non-standard. Some compilers support it as an extension. Use std::vector<char>
instead.
std::vector<char> word(pass.length());
Upvotes: 1