使用类,但无法显示答案。
Working with classes but can't display the answer.
我真的不想写这个问题,但我似乎无法输出名称。这是我班作业的一部分,也是作业中最难的部分,但我的老师说,只要我们真正学习并理解我们在做什么以及为什么要做,我们就可以得到帮助并询问他人。所以我要求这样做是为了帮助我理解为什么我的程序不会输出人名。
我想做的是;输入一个包含大写和小写字母的名称"lEonArDo DA vINCi",以及他们的出生日期"1520",然后输入代码,将该名称转换为小写并仅大写单词中的第一个字母,最后输出该名称。
我一直在输出这个名字。我就是不明白我做错了什么。我问过班上的其他人,但他们还在第一部分,或者在某种程度上被问题卡住了。
class Person{ //Can't change from here.
public:
Person(string n, int year) : name(n), yearOfBirth(year){}
string getName();
friend ostream& operator <<(ostream&, const Person&);
private:
string name; int yearOfBirth;
}; // to here.
string Person::getName() //output the name
{
// I think the output should be here but it doesn't work.
// I have also switched the code in the operator into the getName put it still doesn't work.
return name;
}
ostream& operator << (ostream& output, const Person& P){ //turns everything into lowercase.
locale loc;
string temp = ""; //well be asigning the lowercase letters here; one at a time.
int ii = 0;
for (string::size_type i = 0; i < P.name.length(); i++) { //reads the input one at a time.
if ((ii == 0) || (ii >= 1 && ((P.name[i - 1]) == char(32)))) {(toupper(P.name[i], loc), (temp += toupper(P.name[i], loc))); }//if it was lowercase and the first letter, it turns it into uppercase and assigns it to temp.
else (tolower(P.name[i], loc), (temp += tolower(P.name[i], loc))); //if it was uppercase it turns it into lowercase and assigns it to temp.
ii++;
} //name = temp; //assigns the full lowercase word back to input01.*/
output << temp << " was born in " << P.yearOfBirth;
return output;
}
int main(){
Person::Person("lEonArDo DA vINCi", 1520);
// I have tried putting a output statement here as well
return 0;
}
所以,我的问题是;我应该如何输出名称?(即cout.),我需要把输出语句放在哪里?(在getName或main函数中。)即使你能告诉我一个模糊的答案,它应该在哪里,也会对我有很大帮助。很抱歉我问了一个愚蠢的问题,浪费了你的时间。
Person::Person("lEonArDo DA vINCi", 1520);
不是一个人。你想要的是更多的
Person leonardo("lEonArDo DA vINCi", 1520);
这生成了一个名为leonardo
的类型为Person
的变量,并用"lEonArDo DA vINCi", 1520
对其进行初始化。则可以使用CCD_ 4来访问该CCD_。例如,获取并打印名称
std::cout << leonardo.getName() << std::endl;
或者,由于您已经具有<lt;过载,
std::cout << leonardo <<std::endl;
使用运算符<lt;作用
您可能希望将大写规则从<lt;运算符转换为CCD_ 6构造函数。通过这种方式,您可以存储正确的版本,并在<lt;操作人员这使得<lt;操作要简单得多,并且在构造时只需运行一次校正,而不是每次打印。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 我的程序将 26 个字母转换为 ascII 没有显示正确答案
- 任何人都可以弄清楚这段代码如何显示运行错误?它打印无限时间 -1 以及正确答案
- 如何在 WxWidgets 中显示方程式的答案?
- 删除矢量显示代码 c++ 段时答案更改
- 霍纳斯定律需要代数帮助,显示错误的答案 c++
- 为什么答案不会显示
- 当总和本身显示为180时,当我从两个角度的总和中提取180时,我会得到错误的答案
- 牛顿方法找到立方根,答案每次都显示为0
- 以C++显示时带有单引号和双引号的不同答案
- C++测验:使用矢量正确循环显示答案选项
- 如何使按钮显示随机答案
- C++构造函数并使其显示默认答案
- 为什么此代码不显示计算的正确答案,为什么它会无限循环?
- C++字符串。为什么答案显示字符串"狗"大于"猫",然后"猫"大于"狗"?
- 如何在程序中显示cin答案
- 使用类,但无法显示答案。
- 如何在c++中显示超过1小数点长的答案
- 阶乘在main中显示错误的答案.在函数中正确计算
- Xcode C++程序结果未显示正确答案