This is the piece of code I have. I am new, but enthusiastically learning c++. I am curious to why when I try to declare a new variable first_letter
as a string, to hold the value of my previous string variable greetings
first letter, this error code appears. No viable conversion from 'std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::value_type' (aka 'char') to 'std::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >')
int main()
{
std::string greetings = "hello";
std::string first_letter = greetings[0];
std::cout<<first_letter;
return 0;
}
I understand bit about char and how it holds characters as an integer and is interchangeable. Feel free to explain it as hard as you need, I will look up your detailed things on google as well to learn them. Thank you.
There is no implicit conversion from char to string. You can use the constructor
std::string first_letter(1, greetings[0]);
or
std::string first_letter(greetings, 0, 1);
There is no implicit constructor of std::string
that takes a char
. However, you can construct the string from a char
like this:
std::string first_letter { greetings[0] };
Here's a demo .
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.