1

Is there an equivalent one-liner to '#'*number, which if number was 4 the output of that expression would be "####", in C++? If there isn't an equivalent one-liner, I would like to know if there are any quick ways to do this that don't include a for loop.

Note: I am using C++ 14, on the program I'm working with I can't use C++1z (17), so no C++1z suggestions.

martineau
  • 119,623
  • 25
  • 170
  • 301
Andria
  • 4,712
  • 2
  • 22
  • 38
  • 1
    No. Use a for loop, where the iteration count is one less than the number you want, assuming your iteration count starts at 0 – Nick Meyer Apr 15 '17 at 02:12
  • @NickMeyer Are you sure there aren't any other ways? – Andria Apr 15 '17 at 02:12
  • There might be some library that could handle that, but as far as I am aware, there is not. – Nick Meyer Apr 15 '17 at 02:13
  • Are you using a string? There is a fill constructor `string(size_t n, char c)`. http://www.cplusplus.com/reference/string/string/string/ – twain249 Apr 15 '17 at 02:14
  • See http://stackoverflow.com/questions/7897163/stdcout-to-print-character-n-times and http://stackoverflow.com/questions/166630/how-to-repeat-a-string-a-variable-number-of-times-in-c – Juan T Apr 15 '17 at 02:14
  • Yes, I am using a string, thank you @twain249. If you could post an answer with an example I'll accept it. – Andria Apr 15 '17 at 02:15

2 Answers2

5

As std::string constructor provides an option. Can be done simple as:

std::string(4, '#');

Sample program:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    cout << string(4, '#') << endl;
}
Pavel P
  • 15,789
  • 11
  • 79
  • 128
5

As I stated in the comments there is a fill constructor in the std::string in c++.

string(size_t n, char c);

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

twain249
  • 5,666
  • 1
  • 21
  • 26