【发布时间】:2015-10-28 04:18:14
【问题描述】:
我有一个 c++ 类的作业,我必须将 cstring 用于字符串。
分配应该是一个程序,它接受用户输入的名字和姓氏。然后程序必须将名字的第一个字母转换为大写。还将姓氏的最后一个字母转换为大写。我能够找到一种将名字的第一个字母转换为大写的方法;但是不能用大写字母替换小写字母。另外,不知道怎么把姓氏的最后一个字母大写。
这是与问题相关的部分代码。
#include <iostream>
#include <cstring>
#include <cctype>
using std::cout;
using std::cin;
int main()
{
//Variable Declaration
char firstName[50];
char secondName[50];
char second[50];
char firstLetter;
int result;
int charLength;
//Program Header
cout << "\t\t>>>>>>>> Welcome to The Bog Office of Names <<<<<<<<";
cout << "\nEnter first name: ";
cin >> firstName;
cout << "\nEnter second name: ";
cin >> secondName;
firstLetter= toupper(secondName[0]);
firstLetter = toupper(firstLetter);
cout << "\nFormatted name: " << secondName << " " << firstName;
return 0;
}
【问题讨论】:
-
你有没有想过,比如将大写字母的值赋回字符串的第一个位置?
-
为什么在上一行已经转换为大写的字母上调用
toupper? -
secondName[0]是姓氏的第一个字母。你的任务是写姓氏的最后一个字母,不是吗? -
一般cmets。而不是
char的数组使用std::string。调用 C 库的toupper时,请注意参数必须为非负数或EOF,即您应该将其转换为unsigned char,除非您将自己限制为 ASCII,其中没有负值。使用基于char的文本、窄文本,代码仅限于单字节字符集,例如没有 UTF-8。为了处理 Unicode,您需要使用宽文本,例如wchar_t基于文本。以及相应的流。为此,在 Windows 中,更好地配置这些流以正确处理 Windows 控制台 i/o。 -
干杯,我想过重新分配,但我不知道该怎么做。
标签: c++