Alex Rivera | Logout

Multiplying a string by an int in C++

Asked 2012-08-07T09:44:00.460
28

What do I have to do so that when I

string s = ".";

If I do

cout << s * 2;

Will it be the same as

cout << "..";

?

Edit
Report

1 Answer

2

They can't be multipled but I think you can write your own function to do this, something like -

#include <iostream>
#include <string>

std::string operator*(std::string s, size_t count)
{
    std::string ret;
    for(size_t i = 0; i < count; ++i)
    {
        ret = ret + s;
    }
    return ret;
}


int main()
{
    std::string data = "+";
    std::cout << data * 10 << "\n";
}

It's probably not the best idea though, it will be very confusing to anyone looking at the code and not expecting this,

answered 2012-08-07T11:09:53.823

Your Answer