13

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!

4 Answers 4

26
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.

Sign up to request clarification or add additional context in comments.

5 Comments

What if I want to pass the number of spaces as a parameter
5 can be replaced by a variable.
I wouldn't refer to the foot-note using * - it looks like a pointer ;)
@Georg Fritzsche, I changed it to a double dagger, but there's not much I can do without being able to superscript it :(
Why is this answer upvoted more often compared to the one provided by cape1232? His way looks more clean to me.
9
#include <string> std::string mystring(5,' '); 

Comments

7
#include <string> ..... //i is your variable length string s_blanks_length_i( i, ' ' ); 

Comments

5

5 spaces to standard output:

std::cout << std::string( 5, ' ' ) << std::endl; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.