【问题标题】:uppercase and lowercase in cc中的大写和小写
【发布时间】:2014-07-08 06:38:29
【问题描述】:

我试图弄清楚为什么该程序不起作用。它将小写转换为大写,假设我输入“k”,它返回 K。然后我继续输入“A”,它不返回“a”,而是退出。但为什么?代码如下:

#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();

}

【问题讨论】:

  • 当您在调试器中运行它或打印UPPERLOWER(BTW 变量名错误,请尝试upperlower)它们的值是什么?

标签: uppercase lowercase


【解决方案1】:

如果你编译并运行这段代码:

    void main(void)
    {
        char c = getchar();
        printf("c = %d %c\n", c, c);
        c = getchar();
        printf("c = %d %c\n", c, c);
    }

你会看到这个输出:

    user@host ~/work/tmp $ ./test
    a
    c = 97 a
    c = 10 
    /* new line there*/

这段代码不一样,但有效:

    #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;
    }

【讨论】:

    【解决方案2】:

    你应该在printf("The UPPERCASE now is %c\n", UPPER);之后单独添加getchar();printf("The lowercase now is %c\n", LOWER); 之后再次出现。 大部分程序都是以getch()结尾的,所以我们认为getch()是用来显示输出的……但是错了,它是用来从控制台获取单个字符的。 你正确的代码应该是这样的:

    #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();
    }
    

    【讨论】:

    • 现在我只需要将所有代码放入一个while循环中,直到我进入EOF。有什么建议吗?
    • 没问题,但是我被EOF卡住了,不知道如何在while循环中正确使用它
    • 我不明白你的查询,你想在最后打印两个值吗?
    • 我的意思是:我需要在while循环中使用EOF,但是EOF不起作用。
    猜你喜欢
    • 2012-11-13
    • 2016-07-15
    • 2013-01-25
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    相关资源
    最近更新 更多