Multiply char by integer (c++)(将 char 乘以整数 (c++))
问题描述
char 可以乘 int 吗?
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
推荐答案
我不会称该操作为乘法",这只是令人困惑.串联是一个更好的词.
I wouldn't call that operation "multiplication", that's just confusing. Concatenation is a better word.
无论如何,名为 std::string 的 C++ 标准字符串类有一个非常适合您的构造函数.
In any case, the C++ standard string class, named std::string, has a constructor that's perfect for you.
string ( size_t n, char c );
内容被初始化为由字符c、n次重复形成的字符串.
Content is initialized as a string formed by a repetition of character c, n times.
所以你可以这样:
char star = '*';
int num = 7;
std::cout << std::string(num, star) << std::endl;
确保包含相关的标题,<string>.
Make sure to include the relevant header, <string>.
这篇关于将 char 乘以整数 (c++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 char 乘以整数 (c++)
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
