John
John

Reputation: 193

C++11 string capacity and initialize

In the following code:

string str = "abc";
str.reserve(20);

str.at(10) = 'd'; //LINE1
str[10] = 'd';    //LINE2

Both LINE1 and LINE2 will fail because although str has capacity of 20, but the index at 10 has not been initialized yet. In this kind of situation, how to initialize the the rest of the capacity? push_back() will work, but I have to keep calling push_back() until the index 10 location is initialized.

Upvotes: 2

Views: 196

Answers (2)

Praetorian
Praetorian

Reputation: 109159

Use basic_string::resize.

string str = "abc";
str.resize(11);      // will append 8 value (zero) initialized chars
// or
str.resize(11, ' '); // appends 8 ' ' (spaces)

Upvotes: 6

user3159253
user3159253

Reputation: 17455

you need str.append(10, ' ');. Replace ' ' with any character you wish to use to fill the beginning of the string.

Upvotes: 0

Related Questions