2015-12-07 49 views
1

我的程序應該計算輸入字符串中的元音,輔音,數字和空格的數量。它只計算數字的數量。請幫忙。isspace和isalpha不計數

#include<iostream> 
using namespace std; 

void counter(char string[], int count[]){ 
    int check_letter, check_digit, check_space; 
    for(int i = 0; i < 99; i++){ 
     check_letter = isalpha(string[i]); 
     if(check_letter == 1){ 
      string[i] = tolower(string[i]); 
      if(string[i] == 'a' || string[i] == 'e' || string[i] == 'i' || 
        string[i] == 'o' || string[i] == 'u'){ 
       count[0] = count[0] + 1; 
      } else{ 
       count[1] = count[1] + 1; 
      } 
     } 
     check_digit = isdigit(string[i]); 
     if (check_digit == 1){ 
      count[2] = count[2] + 1; 
     } 
     check_space = isspace(string[i]); 
     if(check_space == 1){ 
      count[3] = count[3] + 1; 
     } 
    } 
} 

main(){ 
    char string[100] = {}; 
    int count[4] = {}; 
    cout << "Please enter a string: "; 
    cin.get(string, 100); 
    cin.get(); 
    cout << string; 
    counter(string, count); 
    cout << "There are " << count[0] << " vowels.\nThere are " << count[1] << 
      " consonants.\nThere are " << count[2] << " digits.\nThere are " << 
      count[3] << " spaces."; 
} 

回答

0

我已經修改你的程序,它適用於我。您可以直接在if()語句中檢查isalpha()isdigit()的返回值,就像它們是bools一樣。

#include<iostream> 
using namespace std; 

void counter(char string[], int count[]){ 
    for(int i = 0; i < 99; i++){ 
     if(isalpha(string[i])){ 
      string[i] = tolower(string[i]); 
      if(string[i] == 'a' || string[i] == 'e' || string[i] == 'i' || 
        string[i] == 'o' || string[i] == 'u'){ 
       count[0] = count[0] + 1; 
      } else{ 
       count[1] = count[1] + 1; 
      } 
     } 
     if (isdigit(string[i])){ 
      count[2] = count[2] + 1; 
     } 
     if(isspace(string[i])){ 
      count[3] = count[3] + 1; 
     } 
    } 
} 

main(){ 
    char string[100] = {}; 
    int count[4] = {}; 
    cout << "Please enter a string: "; 
    cin.get(string, 100); 
    cin.get(); 
    cout << string; 
    counter(string, count); 
    cout << "There are " << count[0] << " vowels.\nThere are " << count[1] << 
      " consonants.\nThere are " << count[2] << " digits.\nThere are " << 
      count[3] << " spaces."; 
} 
+0

是的,你可以,但'int check_letter,check_digit,check_space;'是沒用的...... –

3

你的問題是假設isalphaisdigit等返回1當它們匹配:他們的文件說,他們返回一個非零值的「真」和零「假」。

例如,來自std::isalpha docs here

返回值

非零如果字符是字母字符,否則爲零值。

如果存儲結果在bool,或直接在布爾上下文中測試它們(例如if (...)條件,則轉換會爲你做。

1

問題是check_lettercheck_digitcheck_space都應該bool而不是int

所以,改變bool check_letter, check_digit, check_space;以及if(check_letter)而不是if(check_letter == 1)等。

另外請記住,「字符串」不是一個非常聰明的方式命名變量...