Why I can't assign string::back to string?

Viewed 757

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?

3 Answers

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()};

A string is a collection of characters, the back of a string is a character (i.e., just an element of the collection), not a string.

You can achieve what you want by using the following constructor overload of std::string:

std::string s2(1, s1.back());

That is, construct s2 as a one-character-length string with the value s1.back().

Hope you are trying to create a new string s2 out of the last character of string s1. You can achieve that using the solution below:

#include<iostream>
#include<string>
int main()
{
    std::string s1 = "abc!";
    std::string s2;
    s2 = s1.back();
    std::cout << s1;
    std::cout << s2;
    return 0;
}
Related