2012-05-31 34 views
0

我修改了我的代碼以包含一個計數器,它似乎正在工作,但我不喜歡它的實現方式。它似乎要計算每個字母並在單詞結束之前輸出計數。在數組中輸入變量時執行計數器鍵入

#include <stdio.h> 
#include <ctype.h> 
#include <string.h> 
int main (int argc, char** argv) 
{ 
char C; 
char vowels[]={'a','e','i','o','u'}; 
int counter=0; 
    do 
    { 
    C = getchar(); 
    if(memchr(vowels,C, sizeof(vowels))) 
     {printf("*\n"); 
     counter++; 
     printf("%i", counter); 
     } 
    else 
     { 
     printf("%c",C); 
     } 



    }while (C!='Q'); 
} 

我想的是,輸出遊戲的投入會沿着

g*m* 
2 

所有IM現在得到線被somethhing是

g* 
1m* 
2 

還我怎麼能修改代碼,以便大寫字母也讀爲小寫? 有沒有像C中的isupper或islower?

+0

'ctype.h'中有函數'toupper()'和'tolower()'。您可以使用它們來標準化字符。 – nhahtdh

+0

[islower](http://www.cplusplus.com/reference/clibrary/cctype/islower/)和[isupper](http://www.cplusplus.com/reference/clibrary/cctype/isupper/) – hmjd

回答

1

如果您希望計數器僅打印一次,請將其移至do-while循環之外。

#include <stdio.h> 
#include <ctype.h> 
#include <string.h> 
int main (int argc, char** argv) 
{ 
    char C; 
    char vowels[]={'a','e','i','o','u'}; 
    int counter=0; 
    while(1) { 
     C = getchar(); 
     if(C == 'Q') { break; } 
     C = tolower(C); 
     if(memchr(vowels,C, sizeof(vowels))) { 
      printf("*"); 
      counter++; 
     } 
     else 
     { 
      if(C == '\n') { 
       printf("\n%i\n", counter); 
       // reset the vowel counter here (dunno what the actual task is) 
       counter = 0; 
      } else { 
       printf("%c",C); 
      } 
     } 
    } 

    return 0; 
} 
+0

i當我使用你的代碼時得到錯誤:( – user1428720

+0

修正了一點,現在應該工作了幾個打字錯誤 –

+0

Viktor,代碼是如何在編輯後打印計數器的? – user1428720