英文:
C++ function not working properly with default char argument
问题
我有一段代码片段,其中声明了带有char和int类型默认参数的C++函数。
#include <iostream>
using namespace std;
int print(char c = '*', int num = 10);
int print(char c, int num)
{
for (int i = 0; i < num; i++)
{
cout << c << endl;
}
cout << endl;
return 0;
}
int main()
{
int rep;
char letter;
cout << "Enter a character: ";
cin >> letter;
cout << "Enter the number of times it has to repeat: ";
cin >> rep;
print(letter, rep);
print(rep);
print(letter);
return 0;
}
对于 print(rep); 没有输出,尽管给定了字符的默认参数。有任何想法为什么会发生这种情况吗?
我尝试使用默认参数,但char的默认参数不按预期工作,因此没有预期的字符输出。
英文:
I have a snippet of code where C++ functions are declared with default argument of char and int type.
#include <iostream>
using namespace std;
int print(char c = '*', int num = 10);
int print(char c, int num)
{
for (int i = 0; i < num; i++)
{
cout << c << endl ;
}
cout << endl;
return 0;
}
int main()
{
int rep;
char letter;
cout << "Enter a character : ";
cin >> letter;
cout << "Enter the number of times it has to repeat : ";
cin >> rep;
print(letter, rep);
print(rep);
print(letter);
return 0;
}
There is no output for print(rep);
even though default argument for character is given. Any idea why this is happening?
I tried to use default arguments, but default argument of char is not working as intended and there is no intended character output for that.
答案1
得分: 2
参数仍然按顺序排列。只能省略末尾的参数。当你调用print(rep)
时,整数会转换为char
,并默认为num
。如果你输入,比如说,值为“65”(表示‘A’的代码),你会注意到这一点。
英文:
Arguments are still in order. You can only omit arguments from the end. When you call print(rep)
, the integer gets converted to a char
and num
gets defaulted. You'll notice if you enter, say, "65" (the code for 'A') as the value for rep.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论