Michael Hedgpeth
Michael Hedgpeth

Reputation: 7862

How do I construct a std::string with a variable number of spaces?

If I have the following code:

std::string name =   "Michael";
std::string spaces = "       ";

How would I programatically create the spaces string (a string with all spaces, the length matching the name variable)?

Upvotes: 8

Views: 4484

Answers (4)

KaiserJohaan
KaiserJohaan

Reputation: 9240

I assume you know the length of 'name', hereby refered to as nameLength

std::string spaces(nameLength,' ');

Upvotes: 1

user229044
user229044

Reputation: 239382

You can pass a character and a length to a string, and it will fill a string of that length with the given character:

std::string spaces(7, ' ');

You can use the .size() property of std::string to find the length of your name; combined with the above:

std::string name = "Michael";
std::string spaces(name.size(), ' ');

Upvotes: 17

Simon Richter
Simon Richter

Reputation: 29618

std::string spaces(name.size(), ' ');

Upvotes: 6

Syl
Syl

Reputation: 2783

from http://www.cplusplus.com/reference/string/string/string/

std::string spaces(name.length(), ' ');

Upvotes: 9

Related Questions