【问题标题】:Issue using toupper function in c++在 C++ 中使用 toupper 函数的问题
【发布时间】: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++


【解决方案1】:

您只是将大写字母存储到firstLetter,这无济于事:

int len=strlen(secondName);
firstName[0] = toupper(firstName[0]);

要访问最后一个字母,请使用 len-1 作为 len='\0'

secondName[len-1] = toupper(secondName[len-1]);  //notice len-1

【讨论】:

  • 谢谢牧马人,这就像一个大写字母的魅力!感谢所有我认为的人,我还有很多东西要学。
【解决方案2】:

试试这个:

firstName[0] = toupper(firstName[0]);
secondName[0] = toupper(secondName[0]);
secondName[strlen(secondName)-1] = toupper(secondName[strlen(secondName)-1]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    相关资源
    最近更新 更多