该环路在满足条件时不会结束

时间:2013-03-17 21:44:56

标签: c while-loop

我正在尝试编写一个程序来获取一个字符,然后检查并打印它是大写还是小写。然后我希望它继续循环,直到用户输入“0”,这应该产生一个消息。什么是行不通的是底部的条件,似乎永远不会满足条件。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int ch,nope;    // Int ch and nope variable used to terminate program
    do       // start 'do' loop to keep looping until terminate number is entered
    {
        printf("Enter a character : ");             // asks for user input as a character
        scanf("%c",&ch);                            // stores character entered in variable 'ch'
        if(ch>=97&&ch<=122) {                       // starts if statement using isupper (in built function to check case)
            printf("is lower case\n");
        } else {
            printf("is upper case\n");
        }
    }
    while(ch!=0);                                     // sets condition to break loop ... or in this case print message
    printf("im ending now \n\n\n\n\n",nope);     // shows that you get the terminate line

}

1 个答案:

答案 0 :(得分:2)

尝试while(ch!=48);,因为48是字符'0'的十进制数。 正如Maroun Maroun所说,(ch!='0');更容易理解。

如果您不希望在用户输入“0”时显示大写消息,您可以执行以下操作:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    unsigned char ch,nope;    // Int ch and nope variable used to terminate program
    while (1)
    {
        printf("Enter a character : ");             // asks for user input as a character
        scanf("%c",&ch);                            // stores character entered in variable 'ch'
        if(ch==48) {
            break;
        }
        if(ch>=97&&ch<=122) {                      // starts if statement using isupper (in built function to check case)
            printf("is lower case\n");
        } else {
            printf("is upper case\n");
        }

    }
    printf("im ending now \n\n\n\n\n",nope);     // shows that you get the terminate line

}