How to create std :: string with a variable number of spaces?

If I have the following code:

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

How would I programmatically create a spaces string (a string with all spaces, a length corresponding to a name variable)?

+7
source share
4 answers

You can pass a character and 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() std :: string property to find the length of your name; in combination with the above:

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

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

 std::string spaces(name.length(), ' '); 
+9
source
 std::string spaces(name.size(), ' '); 
+6
source

I assume you know the length of "name" referred to as nameLength

 std::string spaces(nameLength,' '); 
+1
source

All Articles