c - 如何将首字母转换为大写?

标签 c

我正在尝试设计一个简单的程序来询问用户名,但是当稍后使用输入的用户名时,它的首字母应该大写。
我该怎么做?

#include <stdio.h>
#include <string.h> 
#include <ctype.h>
#include <stdlib.h>

int main() {
    char name[30];
    printf("What is your name?\n");
    scanf("%s", name);
    char n = toupper(name);
    printf("Hello %s. Could you tell us a bit about yourself?", n);
}

最佳答案

这条线错了

char n = toupper(name);

toupper 函数需要一个字符,你传递的是一个指针 到一个角色。

正确的版本:

char n = toupper(name[0]);

这一行也是错的

printf("Hello %s. Could you tell us a bit about yourself?", n);

格式说明符 %s 需要一个由 char 指针传递的字符串,你 正在传递单个字符。编译器应该已经警告过你了。 不要忽略编译器警告。

您想更改缓冲区中的第一个字母。所以你必须保存 将字母转换回缓冲区。

name[0] = toupper(name[0]);
printf("Hello %s. Could you tell us a bit about yourself?", name);

关于c - 如何将首字母转换为大写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48492597/

相关文章:

c - 通过指针访问数组时出现段错误

c - 如何减少程序的堆大小以查看它在内存不足时的行为?

c - 为什么我的链接列表实现中的 Push() 函数显示这种行为?

ESP32 的 Core 1 和 0 不能单独工作

c - 为什么在这种情况下使用 LONG_MAX 有效,但使用 FLT_MAX 不起作用?

c - Beaglebone Black 上的 GPIO

使用 GTK 创建新文件

python - 为什么特定算法通过 ctypes 花费的时间明显更长?

c - 在 C 中初始化 3D 全局数组

在 C 中将大串数字(14 位)转换为整数或长整数