Blue7
Blue7

Reputation: 2044

Remove last character of std::string_view

I'm trying to remove the last character of an std string view, but no matter what I do it remains there. I think its because I'm accidentally removing the "/0" instead of the desired "]".

Here is my code:

#include <iostream>
#include <tstr/tstring.h>
#include <cstring>

template<typename Class>
constexpr const char* to_string() {
    std::string_view str = __PRETTY_FUNCTION__;
    auto first = str.find("= ");
    auto last = str.find("]");
    auto str2 = str.substr(first + 2, last - first + 1);
    return str2.data();
}

class Foo {};

int main()
{
    std::cout << to_string<Foo>() << std::endl;
    return 0;
}

This outputs Foo]. How can I remove the trailing ] ?

Thanks.

Upvotes: 0

Views: 1184

Answers (1)

eerorika
eerorika

Reputation: 238351

If you insert a pointer to char into a character stream, the pointed string is printed until the null terminator is reached. If there is no null terminator, then the behaviour of the program is undefined.

std::string_view is not guaranteed to be null terminated. Therefore it is dangerous to insert std::string_view::data into a character stream. In this particular case, the string view points to a non-null-terminated substring within a null terminated string, so the behaviour is well defined, but not what you intended because the output will proceed to the outside of the substring.

How can I remove the prepending ] ?

Return the string view to the substring rather than a pointer:

constexpr std::string_view to_string() {
    ...
    return str2;
}

Upvotes: 3

Related Questions