Isspace和IsAlpha不算在内
isspace and isalpha isn't counting
我的程序应该计算输入字符串中元音、辅音、数字和空格的数量。它只计算数字的数量。请帮忙。
#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.";
}
您的问题是假设isalpha
、isdigit
等在匹配时返回1
:他们的文档说他们返回"的非零值;真";而零表示"0";false";。
例如,来自std::isalpha文档此处:
返回值
如果字符是字母字符,则为非零值,否则为零。
如果您将结果存储在bool
中,或直接在布尔上下文中测试它们(例如if (...)
条件),则将为您完成转换。
问题是check_letter
、check_digit
和check_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.";
}
相关文章:
- C++ 中的 ISALPHA 无法正常工作,无法正常工作
- isspace 函数的性能警告,从 int 转换为布尔值
- 使用 isdigit 和 isalpha 设置相等的 char 数组
- 在给定字符串上使用 tolower() 和 isalpha() 并将其输出设置为另一个字符串
- isalpha()?或其他.. Debug断言失败了,CircleMud游戏
- ISALPHA 导致 C++ "Debug Assertion Failed"
- 当使用'isalpha()'是安全的
- Clang std::isspace 编译错误
- 是否可以将isdigit,isalpha函数与输入的字符串数组一起使用
- 我不明白如何将 toupper 和 isalpha 与.txt文件字符串输入一起使用
- 在C++中,为什么<cctype>同时定义std::isspace和::isspace?
- ISSPACE和替换()的问题
- C/C++ isspace() 跳过多字节字符串字符
- std::remove_if 和 std::isspace - 编译时错误
- isalpha() 函数为字符串中的字符返回 false
- 无法使ispunct或isspace工作,但isupper工作正常.你能帮我吗
- 消除C++中std::isalpha()的歧义
- 为什么这个对isspace()的调用永远不会返回true
- 为什么 isalpha() 停在空格处
- Isspace和IsAlpha不算在内