如何在 c++ 中将首字母转换为大写?

How to convert first letter to uppercase in c++?

本文关键字:转换 c++      更新时间:2023-10-16

我有一个结构

struct StudentRecord{
char StudentFamilyName[20]
}gRecs[50];
cout << "Family Name: ";
cin >> gRecs[50].StudentFamilyName;
char str[20];
str[20] = toupper(gRecs[i].StudentFamilyName[0]);
cout << str;

我想做的是将姓氏的第一个字母存储为 大写,其余为小写?我该怎么做? 我用过toupper但是当我实现它不起作用时。谁能帮我?谢谢。

注意:这是一个考试问题。

以下是使用字符算法将字符串大写的方法:

#include <iostream>
#include <string>
using namespace std;

string ToCapitalize(string input)
{
if (input.length() > 1 && input[0] >= 'a' && input[0] <= 'z')
{
input[0] -= 32;
}
return input;
}
int main() {
std::string StudentFamilyName("smith");
cout << StudentFamilyName << std::endl;
cout << "Capitalized: " << ToCapitalize(StudentFamilyName) << endl;
}

你的问题不在于toupper。 实际上,其中有几个。

cin >> gRecs[50]
gRecs

的大小为 50,因此索引 50 超出范围。 要插入到您将使用的第一条记录中

cin >> gRecs[0].StudentFamilyName;

第二张唱片:gRecs[1]

下一个

char str[20];
str[20] = toupper(str[0]);

您声明str其中未填充任何内容,然后对其调用toupper。 索引([20])是第21个字符(越界)。 您正在尝试转换strtoupper中的第 21 个字符。

您需要的是:

// i is the index into your student records array, possibly in a loop
cin >> gRecs[i].StudentFamilyName;
gRecs[i].StudentFamilyName[0] = toupper(gRecs[i].StudentFamilyName[0]);