I write a simple program: Get last character of string1 and assign it to string2. It's like:
#include<iostream>
#include<string>
int main(int argc, char const *argv[])
{
std::string s1 = "abc!";
std::string s2 = s1.back();
std::cout << s1;
return 0;
}
However, I get a compile error:
conversion from ‘__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type {aka char}’ to non-scalar type ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ requested
I don't know this error exactly means. It's seems like some type conversion error occur. But the return value of string::back should be char, right?
Why I can't assign it to another string? And how I can give last character of s1 to s2?
It's because std::string
does not have an implicit constructor which takes just a single character parameter, that's why conversion from char
to std::string
fails. Instead you can use:
// 1. Constructor with length + char
std::string s2(1, s1.back());
// 2. Constructor which takes an std::initializer_list<char>
std::string s2{s1.back()};
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