首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C中的大写和小写

C中的大写和小写
EN

Stack Overflow用户
提问于 2014-07-08 14:38:29
回答 2查看 1.2K关注 0票数 0

我试着弄清楚为什么这个程序不能工作。它将小写转换为大写,假设我输入" K ",它返回K。然后我继续输入"A",它不返回"a",但退出。但是为什么呢?代码如下:

代码语言:javascript
运行
复制
#include <stdio.h>
#include <stdlib.h>


int main(){


char UPPER,LOWER;

printf("Enter UPPERCASE\n");
UPPER = getchar();
if (UPPER >= 65 && UPPER <= 90) 

{ 
    UPPER = UPPER + 32;
    printf("The UPPERCASE now is %c\n", UPPER);

}

printf("Enter lowercase\n");
LOWER = getchar();
if (LOWER >= 97 && LOWER <= 122)

{

    LOWER = LOWER - 32;
    printf("The lowercase now is %c\n", LOWER);

}


getchar();
getchar();

}
EN

回答 2

Stack Overflow用户

发布于 2014-07-08 14:57:57

如果编译并运行以下代码:

代码语言:javascript
运行
复制
    void main(void)
    {
        char c = getchar();
        printf("c = %d %c\n", c, c);
        c = getchar();
        printf("c = %d %c\n", c, c);
    }

您将看到以下输出:

代码语言:javascript
运行
复制
    user@host ~/work/tmp $ ./test
    a
    c = 97 a
    c = 10 
    /* new line there*/

这段代码并不相同,但可以工作:

代码语言:javascript
运行
复制
    #include <stdlib.h>
    #include <stdio.h>

    #define BUFSIZE 4
    int main(void)
    {
        char UPPER[BUFSIZE] = {0}, LOWER[BUFSIZE] = {0};
        int i;

        printf("Enter UPPERCASE\n");
        fgets(UPPER, BUFSIZE, stdin);
        for(i = 0; i < BUFSIZE; i++)
        {
            if (UPPER[i] >= 65 && UPPER[i] <= 90) 

            { 
                UPPER[i] = UPPER[i] + 32;
            }
        }
        printf("The UPPERCASE now is %s", UPPER);

        printf("Enter LOWERCASE\n");
        fgets(LOWER, BUFSIZE, stdin);

        for(i = 0; i < BUFSIZE; i++)
        {
            if (LOWER[i] >= 97 && LOWER[i] <= 122) 

            { 
                LOWER[i] = LOWER[i] - 32;
            }
        }
        printf("The LOWERCASE now is %s", LOWER);
        return 0;
    }
票数 0
EN

Stack Overflow用户

发布于 2014-07-08 15:06:24

您应该分别在printf("The UPPERCASE now is %c\n", UPPER);之后添加getchar();,并在printf("The lowercase now is %c\n", LOWER);之后再次添加。大部分程序都以getch()结尾,因此我们认为getch()用于显示output...but,而wrong.It用于从控制台获取单个字符。正确的代码应该如下所示:

代码语言:javascript
运行
复制
#include <stdio.h>
#include <stdlib.h>
int main()
{
char UPPER, LOWER;
printf("Enter UPPERCASE\n");
UPPER = getchar();
if (UPPER >= 65 && UPPER <= 90)

{
UPPER = UPPER + 32;
printf("The UPPERCASE now is %c\n", UPPER);

}
getchar();
printf("Enter lowercase\n");
LOWER = getchar();
if (LOWER >= 97 && LOWER <= 122)

{

LOWER = LOWER - 32;
printf("The lowercase now is %c\n", LOWER);

}
getchar();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24625187

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档