c++ - 在 C++ 中使用 toupper 函数的问题

标签 c++

我有一个 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/

相关文章:

python - 将基数设置为未确定大小的对象

c++ - 如何在构造函数上正确使用 std::enable_if

c++ - 容量是否复制到 vector 中?

c# - C++ vs C#,性能方面的选择(VS2010)

c++ - 链接 : fatal error LNK1104: cannot open file 'libcollada14dom21.lib'

php - C++ 从 http 下载二进制文件

c++ - 使用双指针声明二维数组

c++ - boost::date_time::days_until_weekday 的编译错误

c++ - 现代 C++ 编译器可以内联 cpp 文件中定义的函数吗

c++ - 为什么 cin.get() 函数可以去除字符串中的 '\n'?