将字符乘以整数 (c++)
是否可以将 char 与 int 相乘?
例如,我正在尝试制作一个图表,每次出现数字时都用 * 表示。
就像这样,但这不起作用
char star = "*";
int num = 7;
cout << star * num //to output 7 stars
Is it possible to multiply a char by an int?
For example, I am trying to make a graph, with *'s for each time a number occurs.
So something like, but this doesn't work
char star = "*";
int num = 7;
cout << star * num //to output 7 stars
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我不会将该操作称为“乘法”,这只是令人困惑。连接是一个更好的词。
无论如何,名为
std::string
的 C++ 标准字符串类有一个非常适合您的构造函数。内容被初始化为由字符
c
重复n
次形成的字符串。因此,您可以这样操作:
确保包含相关标头
。I wouldn't call that operation "multiplication", that's just confusing. Concatenation is a better word.
In any case, the C++ standard string class, named
std::string
, has a constructor that's perfect for you.Content is initialized as a string formed by a repetition of character
c
,n
times.So you can go like this:
Make sure to include the relevant header,
<string>
.您这样做的方式是将
'*'
字符的二进制表示形式与数字 7 进行数字乘法,并输出结果数字。你想要做的(基于你的c++代码注释)是这样的:
the way you're doing it will do a numeric multiplication of the binary representation of the
'*'
character against the number 7 and output the resulting number.What you want to do (based on your c++ code comment) is this:
GMan 对这个问题的过度设计启发了我进行一些模板元编程以进一步过度设计它。
GMan's over-eningeering of this problem inspired me to do some template meta-programming to further over-engineer it.
你可以这样做:
You could do this:
语句应该是:
(star * num) 将 '*' 的 ASCII 值与 num 中存储的值相乘
要输出 '*' n 次,请遵循其他人灌输的想法。
希望这有帮助。
The statement should be:
(star * num) will multiply the ASCII value of '*' with the value stored in num
To output '*' n times, follow the ideas poured in by others.
Hope this helps.
}
}