2013-03-17 58 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