在Python中,有一种方法可以将字符串相乘,例如,“a”*3
将返回“aaa”
。 但是,这种语法在C++中不起作用,它只会给我一个错误,“const char[2]”和“int”类型的操作数无效到二进制“operator*”
。 在C++中,有没有一种方法可以像这样将一个字符串相乘?
C++中没有这样的运算符。
但是您可以编写一个函数,它以一个字符串和一个数字作为参数,并返回重复的字符串。
std::string
还有一个构造函数,它可以多次重复给定的字符。 这可能很有用,因为您使用了一个字符的字符串作为示例。
您可以重载运算符
std::string operator*(const std::string& s, unsigned n)
{
... // your code here
}
您可以执行连接
#include <iostream>
using namespace std;
int main()
{
string a="A";
cout<<"number of times you want to multiply \n";
int num;
cin>>num;
while(num!=1)
{
a+="A";
num--;
}
cout<<a;
return 0;
}