[英]convert char array elemnts to upper or lower case
For my homework assignment we are asked to get a string from the user and: 对于我的家庭作业,我们要求从用户处获取一个字符串,并:
I do not know if my logic is wrong or if it's a simple fix. 我不知道我的逻辑是错误的还是简单的解决方法。 Any suggestions are appreciated.
任何建议表示赞赏。
#include <stdio.h>
int main()
{
int i;
char sentense [30];
printf("Please enter a sentence\n");
fgets(sentense, 30, stdin);
for(i=0; sentense[i] != '\0'; i++)
{
putchar(toupper(sentense[i]));
}
for(i=0; sentense[i] != '\0'; i++)
{
putchar(tolower(sentense[i]));
}
for(i=0; sentense[i] != '\0'; i++)
{
if(sentense[i] >='65' && sentense[i] <='90')
{
putchar(tolower(sentense[i]));
}
else if(sentense[i] >= '97' && sentense[i] <='122')
{
putchar(tolower(sentense[i]));
}
else
{
}
}
return 0;
}
You need to change 你需要改变
if(sentense[i] >='65' && sentense[i] <='90')
to 至
if(sentense[i] >= 65 && sentense[i] <= 90)
and rest case(s) as we want to compare the integer value here. 和其余的情况,因为我们想在这里比较整数值。
Enable the compiler warning and your compiler should be warning you about the mistake. 启用编译器警告,您的编译器应警告您有关错误。
Alternatively, you can also make use of isupper()
/ islower()
library functions, too. 另外,您也可以使用
isupper()
/ islower()
库函数。
isupper
and islower
to prevent the code to depend on character codes. isupper
和islower
来防止代码依赖于字符代码。 toupper
instead of tolower
to convert letters to uppercase. toupper
而不是tolower
将字母转换为大写。 Fixed code: 固定代码:
#include <stdio.h>
#include <ctype.h>
int main()
{
int i;
char sentense [30];
printf("Please enter a sentence\n");
fgets(sentense, 30, stdin);
for(i=0; sentense[i] != '\0'; i++)
{
putchar(toupper(sentense[i]));
}
for(i=0; sentense[i] != '\0'; i++)
{
putchar(tolower(sentense[i]));
}
for(i=0; sentense[i] != '\0'; i++)
{
if(isupper(sentense[i]))
{
putchar(tolower(sentense[i]));
}
else if(islower(sentense[i]))
{
putchar(toupper(sentense[i]));
}
else
{
putchar(sentense[i]);
}
}
return 0;
}
Easy to understand, you should compare directly. 易于理解,您应该直接进行比较。 Let's use:
让我们使用:
if(sentense[i] >='A' && sentense[i] <='Z')
to check the up-case. 检查大写。 And use:
并使用:
if(sentense[i] >='a' && sentense[i] <='z')
to check the low-case. 检查小写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.