Short answer: use resize(10) instead of reserve(10)
Long answer:
In the implementation of std::string, there are two variables size and capacity.
Capacity is how much memory you have allocated for the string.
Size is how many valid elements (in your case, char), are allowed in your string.
Note that capacity will always be smaller than or equal to size.
When you call reserve(), you're changing capacity.
When your call resize(), you might NOT only be changing size, but you will also changing capacity if size > capacity, in which this formula would then applies:
if (size > capacity){
capacity = max(size, capacity*2); //Why multiply capacity by 2 here? This is to achieve amortized O(1) while resizing
}
Here's a code example of what OP wants and some more code for a better explanation of size and capacity
#include <iostream>
#include <string.h>
using namespace std;
int main(int argc, char const *argv[])
{ const char *s1 = "hello";
string s2;
s2 = s1;
cout << "length of s2 before reserve: " << s2.length() << endl;
cout << "capacity of s2 before reserve: " << s2.capacity() << endl;
s2.reserve(10);
cout << "length of s2 after reserve: " << s2.length() << endl; //see how length of s2 didn't change?
cout << "capacity of s2 after reserve: " << s2.capacity() << endl;
s2.resize(8); //resize(10) works too, but it seems like OP you only need enough size for 8 elements
cout << "length of s2 after resize: " << s2.length() << endl; //size changed
cout << "capacity of s2 after resize: " << s2.capacity() << endl; //capacity didn't change because size <= capacity
s2[5] = '.';
s2[6] = 'o';
s2[7] = '\0';
cout << "[" << s1 << "] [" << s2 << "]" << endl;
// You're done
// The code below is for showing you how size and capacity works.
s2.append("hii"); // calls s2.resize(11), s[8] = 'h', s[9] = 'i', s[10] = 'i', size = 8 + 3 = 11
cout << "length of s2 after appending: " << s2.length() << endl; // size = 11
cout << "capacity of s2 after appending: " << s2.capacity() << endl; //since size > capacity, but <= 2*capacity, capacity = 2*capacity
cout << "After appending: [" << s1 << "] [" << s2 << "]" << endl;
return 0;
Result:
length of s2 before reserve: 5
capacity of s2 before reserve: 5
length of s2 after reserve: 5
capacity of s2 after reserve: 10
length of s2 after resize: 8
capacity of s2 after resize: 10
[hello] [hello.o]
length of s2 after appending: 11
capacity of s2 after appending: 20
After appending: [hello] [hello.ohii]