我有一个 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;
}
最佳答案
你只是将大写字母存储到 firstLetter
这没有帮助:
int len=strlen(secondName);
firstName[0] = toupper(firstName[0]);
要访问最后一个字母,请使用 len-1
作为 len='\0'
secondName[len-1] = toupper(secondName[len-1]); //notice len-1
关于c++ - 在 C++ 中使用 toupper 函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33382829/