Isspace和IsAlpha不算在内

isspace and isalpha isn't counting

本文关键字:IsAlpha Isspace      更新时间:2023-10-16

我的程序应该计算输入字符串中元音、辅音、数字和空格的数量。它只计算数字的数量。请帮忙。

#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.";
}

您的问题是假设isalphaisdigit等在匹配时返回1:他们的文档说他们返回"的非零值;真";而零表示"0";false";。

例如,来自std::isalpha文档此处:

返回值

如果字符是字母字符,则为非零值,否则为零。

如果您将结果存储在bool中,或直接在布尔上下文中测试它们(例如if (...)条件),则将为您完成转换。

问题是check_lettercheck_digitcheck_space都应该是bool,而不是int

因此,更改bool check_letter, check_digit, check_space;if(check_letter),而不是if(check_letter == 1),依此类推

此外,请记住,"字符串"不是一种非常聪明的变量命名方式。。。

我修改了你的程序,它对我来说很好。你可以直接在if()语句中检查isalpha()isdigit()的返回值,就像它们是布尔一样。

#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.";
}