2013-03-17 61 views
0

我想写一个程序来获取一个字符,然后检查并打印它是否使用大写或小写。然后,我希望它保持循环,直到用户输入一个应该产生消息的“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

'CH = 0'是错误的,应该是' ch!='0'' – Maroun 2013-03-17 21:53:17

+0

幻数97和122是个不错的主意。使用''a''和''z'',或者只需调用''中声明的'islower()'。此外,代码还会为数字和标点符号报告“大写”。 – 2013-03-17 22:20:55

回答

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 

} 
+0

这很有效!辉煌。但由于某些原因,它会打印大写语句以及打印terminate语句。 – user2180343 2013-03-17 21:55:04

+0

这是因为您正在检查的条件发生在while循环的末尾。首先执行代码,然后检查条件。 – Silox 2013-03-17 21:56:38

+0

感谢您的帮助。我会尝试修复它 – user2180343 2013-03-17 21:59:29