c中的大写和小写

时间:2014-07-08 06:38:29

标签: uppercase lowercase

我试图找出程序无效的原因。它将小写变为大写,假设我输入“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();

}

2 个答案:

答案 0 :(得分:0)

如果您编译并运行此代码:

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

答案 1 :(得分:0)

您应该在getchar();之后单独添加printf("The UPPERCASE now is %c\n", UPPER); 并在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();
}