我的程序应该计算输入字符串中的元音,辅音,数字和空格的数量。它只计算位数。请帮忙。
#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 :(得分:3)
您的问题是假设isalpha
,isdigit
等匹配时返回1
:他们的文档说他们为“true”返回非零值,为“假”。
例如,来自std::isalpha docs here:
返回值
如果字符是字母字符,则为非零值,否则为零。
如果您将结果存储在bool
中,或直接在布尔上下文中测试它们(例如if (...)
条件,那么转换将为您完成。
答案 1 :(得分:1)
问题是check_letter
,check_digit
和check_space
都应该是bool
而不是int
。
因此,请更改bool check_letter, check_digit, check_space;
以及if(check_letter)
而不是if(check_letter == 1)
,依此类推。
另外请记住,“string”不是命名变量的一种非常聪明的方法......
答案 2 :(得分:0)
我修改了你的程序,它对我来说很好。您可以直接在if()语句中检查isalpha()isdigit()的返回值,就好像它们是bool一样。
#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.";
}