gpt4 book ai didi

C - 想要使用符号转换大小写字母

转载 作者:太空狗 更新时间:2023-10-29 16:10:15 24 4
gpt4 key购买 nike

我想在 C 语言中将小写字母转换为大写字母,反之亦然。我已经这样做了,但是当我使用像“_”或“.”这样的符号时或 ',' .... 在输入中,我在输出中得到随机字符,例如正方形内的问号。

INPUT: AAbb
OUTPUT: aaBB
INPUT: a_A
OUTPUT: A⍰a

我怎样才能使用符号使其工作?

代码:

#include <stdio.h>

int main(void)
{
char a[50];
int x = 1;

while( x > 0){
gets(a);
int i,length=0;
for(i=0;a[i]!='\0';i++)
length+=1;
for(i=0;i<length;i++){
a[i]=a[i]^32;
}
printf("%s",&a);
}
}

最佳答案

... convert lowercase and uppercase letters using symbols
... when I use a symbol like '_' or '.' or ',' .... on the input I get random character

使用isupper()tolower()toupper()。这是切换大小写的标准和高度可移植的方式。假设在各种平台上有超过 26 个字母。

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

int main(void ){
char a[50];
{
gets(a); // dubious, consider fgets().
int i,length=0;

for(i=0;a[i];i++){
unsigned char ch = a[i];
if (isupper(ch) {
a[i]= tolower(ch);
} else {
a[i]= toupper(ch);
}
}
printf("%s",a); // use `a` , not `&a`
}
}

如果代码想在不使用标准函数的情况下切换大小写,并且已知 char 是一个字母,代码可以使用以下代码。它合理地假设 A-Z 和 a-z 相差一位,就像 ASCII 中的情况一样。和 EBCDIC

        // Avoid magic numbers like 32
a[i] ^= 'a' ^ 'A';

仍然推荐使用标准函数。

关于C - 想要使用符号转换大小写字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49971963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com