Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

c++11

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?

like image 486
CodePurin Avatar asked Jan 02 '23 17:01

CodePurin


1 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()};
like image 102
Oleg Andriyanov Avatar answered Jan 05 '23 18:01

Oleg Andriyanov