我的程序应该计算输入字符串中元音、辅音、数字和空格的数量。只是数数字而已。请帮帮忙。
#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.";
}发布于 2015-12-07 06:33:35
我修改了你的程序,它对我很好。您可以在if ()语句中直接检查isalpha() is位()的返回值,就像它们是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.";
}发布于 2015-12-07 05:15:04
您的问题是假设isalpha、isdigit等在匹配时返回1:它们的文档表示返回"true“的非零值,"false”的返回值为零。
例如,来自std:isalpha文档在这里
返回值 如果字符是字母字符,则为非零值,否则为零。
如果将结果存储在bool中,或者直接在布尔上下文中测试结果(例如,if (...)条件),那么转换将为您完成。
发布于 2015-12-07 06:14:17
问题是check_letter、check_digit和check_space都应该是bool,而不是int。
因此,改变bool check_letter, check_digit, check_space;和if(check_letter),而不是if(check_letter == 1)等等。
同时,请记住,"string“并不是一个非常聪明的命名变量的方法。
https://stackoverflow.com/questions/34126779
复制相似问题