tags:

views:

124

answers:

3

I need to create a string of blanks in c++, where the number of spaces is a variable, so I can't just type it in. How do I do this without looping ?

Thanks!

+12  A: 
std::string blanks = "     ";

Or perhaps more useful to you:

size_t size = 5; // size_t is similar to unsigned int ‡
std::string blanks(size, ' ');

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

‡ See the question on size_t if this isn't clear.

Brendan Long
What if I want to pass the number of spaces as a parameter
MLP
Awesome, this is exactly what I was looking for.
MLP
5 can be replaced by a variable.
cape1232
I wouldn't refer to the foot-note using `*` - it looks like a pointer ;)
Georg Fritzsche
@Georg Fritzsche, I changed it to a double dagger, but there's not much I can do without being able to superscript it :(
Brendan Long
Why is this answer upvoted more often compared to the one provided by cape1232? His way looks more clean to me.
Sergej Andrejev
@Sergei Andrejev, I'm guessing it's mostly because I answered before him (by like 30 seconds), and people tend to up-vote the oldest answer. Also, the first section was in response to the original question ("how do I create a string of 5 spaces?"), so it wasn't originally so out of place ;)
Brendan Long
+4  A: 
#include <string>
.....
//i is your variable length
string s_blanks_length_i( i, ' ' );
MadMurf
+5  A: 
#include <string>
std::string mystring(5,' ');
cape1232