dmi
dmi

Reputation: 73

C++: Repeat output i times without an explicit loop

Is there is way to do so without a loop writing as less code as possible:

for (int i = 0; i < 10; i++) std::cout << 'x';

Like in python:

print 'x' * 10

Upvotes: 0

Views: 2852

Answers (5)

booleys1012
booleys1012

Reputation: 731

The most extensible/reusable way is to just create a function similar to Ed, above -- although I'd use a stringstream and not couple the function with the printing

IMO, NPE's answer is too restrictive by forcing it to be a single character only, and Ed's is more of a C answer than a C++ answer. As a side-benifit, the function also allows you to stream characters, integers, strings, etc.

template <class T>
std::string multiplyString(int count, const T &input)
{
    std::stringstream ss;
    for(int i = 0; i < count; i++)
       ss << T;
    return ss.str();
}

int main(argc, char *argv[])
{
    std::cout << multiplyString(10, 'x') << std::endl;
    std::cout << multiplyString(5, "xx") << std::endl;
    std::cout << multiplyString(5, 1234) << std::endl;
}

Best of luck

Upvotes: 1

James Kanze
James Kanze

Reputation: 153909

Since no one else has offered a reasonable implementation:

std::string
multiplyStrings( int count, std::string const& original )
{
    std::string results;
    results.reserve( count * original.size() );  //  Just optimization
    while ( count > 0 ) {
        results += original;
    }
    return results;
}

Creating the overloads for operator* from this would not be difficult. Defining them in namespace std would be undefined behavior, but IMHO, there's a reasonably good chance that you could get away with it anyway.

Upvotes: 0

Robᵩ
Robᵩ

Reputation: 168616

std::generate_n(
    std::ostream_iterator<char>(std::cout, ""),
    10,
    [](){ return 'x'; }
);

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 59997

void print(const char *s, int n)
{
   if (n > 0) 
   {
      cout << s;
      print(s, n - 1);
   }
}

should do the trick.

Upvotes: 3

NPE
NPE

Reputation: 500257

Use the std::string(size_t, char) constructor:

std::cout << std::string(10, 'x');

Note that, unlike in Python, this only works with chars and not with strings.

Upvotes: 7

Related Questions