Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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)?

like image 312
Michael Hedgpeth Avatar asked Jan 26 '11 16:01

Michael Hedgpeth


People also ask

Can a string variable have spaces?

Naming rulesSpaces are not allowed in variable names, so we use underscores instead of spaces.

Can C++ string have space?

In this case, string will be terminated as spaces found, this only "Vanka" will be stored in variable name. Now, how to read string with spaces in C++? We can use a function getline(), that enable to read string until enter (return key) not found.


1 Answers

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(), ' ');
like image 96
meagar Avatar answered Nov 07 '22 18:11

meagar