Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a string of fixed size

Tags:

c++

In C we do

char buffer[100];

Is there a way to declare a fixed size std::string?

like image 928
user3600124 Avatar asked Aug 22 '16 14:08

user3600124


3 Answers

I don't know what you want to do, but with an std::array<char, 100> buffer; you should do fine.

You can then get a string like this:

std::string str(std::begin(buffer),std::end(buffer);
like image 101
Drayke Avatar answered Sep 19 '22 13:09

Drayke


You can use the string::reserve method like this

  std::string s;
  s.reserve(100);

But this isn't fixed size, because you can add more chars to the string with string::push_back for example.

like image 11
pospich0815 Avatar answered Oct 20 '22 22:10

pospich0815


In c++17, there will be std::string_view which offers the same (immutable) interface as std::string.

In the meantime, you can wrap a char array and add whatever services to it you choose, eg:

template<std::size_t N>
struct immutable_string
{
    using ref = const char (&)[N+1];
    constexpr immutable_string(ref s)
    : s(s)
    {}

    constexpr auto begin() const { return (const char*)s; }
    constexpr auto end() const { return begin() + size(); }
    constexpr std::size_t size() const { return N; }
    constexpr ref c_str() const { return s; }
    ref s;

    friend std::ostream& operator<<(std::ostream& os, immutable_string s)
    {
        return os.write(s.c_str(), s.size());
    }
};

template<std::size_t NL, std::size_t NR>
std::string operator+(immutable_string<NL> l, immutable_string<NR> r)
{
    std::string result;
    result.reserve(l.size() + r.size());
    result.assign(l.begin(), l.end());
    result.insert(result.end(), r.begin(), r.end());
    return result;
}

template<std::size_t N>
auto make_immutable_string(const char (&s) [N])
{
    return immutable_string<N-1>(s);
}

int main()
{
    auto x = make_immutable_string("hello, world");
    std::cout << x << std::endl;

    auto a = make_immutable_string("foo");
    auto b = make_immutable_string("bar");
    auto c = a + b;
    std::cout << c << std::endl;
}
like image 6
Richard Hodges Avatar answered Oct 20 '22 23:10

Richard Hodges