I want to insert 'n' spaces (or any string) at the beginning of a string in C++. Is there any direct way to do this using either std::strings or char* strings?
E.g. in Python you could simply do
>>> "." * 5 + "lolcat"
'.....lolcat'
I want to insert 'n' spaces (or any string) at the beginning of a string in C++. Is there any direct way to do this using either std::strings or char* strings?
E.g. in Python you could simply do
>>> "." * 5 + "lolcat"
'.....lolcat'
std::string foo = std::string(5, '.') + "lolcat";
Check out std::string's constructors.
You should write your own stream manipulator
cout << multi(5) << "whatever" << "lolcat";
Use one of the forms of string::insert:
std::string str("lolcat");
str.insert(0, 5, '.');
This will insert "....." (five dots) at the start of the string (position 0).
There's no direct idiomatic way to repeat strings in C++ equivalent to the * operator in Python or the x operator in Perl. If you're repeating a single character, the two-argument constructor (as suggested by previous answers) works well:
std::string(5, '.')
This is a contrived example of how you might use an ostringstream to repeat a string n times:
#include <sstream>
std::string repeat(int n) {
std::ostringstream os;
for(int i = 0; i < n; i++)
os << "repeat";
return os.str();
}
Depending on the implementation, this may be slightly more efficient than simply concatenating the string n times.
I know this is an old question, but I was looking to do the same thing and have found what I think is a simpler solution. It appears that cout has this function built in with cout.fill(), see the link for a 'full' explanation
http://www.java-samples.com/showtutorial.php?tutorialid=458
cout.width(11);
cout.fill('.');
cout << "lolcat" << endl;
outputs
.....lolcat