dub*_*bya 7 c++ string char multiplying
是否可以将char乘以int?
例如,我正在尝试制作一个图表,每次出现一个数字都带有*.
所以类似的东西,但这不起作用
char star = "*";
int num = 7;
cout << star * num //to output 7 stars
Run Code Online (Sandbox Code Playgroud)
jan*_*nks 22
我不会把那个操作称为"乘法",这只是令人困惑.连接是一个更好的词.
在任何情况下,名为C++标准的字符串类std::string都有一个非常适合您的构造函数.
string ( size_t n, char c );
Run Code Online (Sandbox Code Playgroud)
内容被初始化为由重复的字符c,n时间形成的字符串.
所以你可以这样:
char star = '*';
int num = 7;
std::cout << std::string(num, star) << std::endl;
Run Code Online (Sandbox Code Playgroud)
确保包含相关标题<string>.
你正在做的方式是将'*'字符的二进制表示与数字7 进行数字相乘,然后输出结果数.
您想要做什么(基于您的c ++代码注释)是这样的:
char star = '*';
int num = 7;
for(int i=0; i<num; i++)
{
cout << star;
}// outputs 7 stars.
Run Code Online (Sandbox Code Playgroud)
GMan对这个问题的过度关注激发了我做一些模板元编程以进一步过度设计它.
#include <iostream>
template<int c, char ch>
class repeater {
enum { Count = c, Char = ch };
friend std::ostream &operator << (std::ostream &os, const repeater &r) {
return os << (char)repeater::Char << repeater<repeater::Count-1,repeater::Char>();
}
};
template<char ch>
class repeater<0, ch> {
enum { Char = ch };
friend std::ostream &operator << (std::ostream &os, const repeater &r) {
return os;
}
};
main() {
std::cout << "test" << std::endl;
std::cout << "8 r = " << repeater<8,'r'>() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)