简体   繁体   English

C 布尔类型函数总是返回 FALSE

[英]C boolean type function always returns FALSE

My assignment is to make a program that takes a string and output:我的任务是制作一个接受字符串和输出的程序:

the number of characters in the string
the number of vowels in the string
the number of UPPERCASE letters in the string
the number of lowercase letters in the string
the number of other characters in the string

We are not allowed to use the ctype.h library.我们不允许使用 ctype.h 库。 Right now I'm just trying to output the number of vowels.现在我只是想输出元音的数量。

#include<stdio.h>
#include<string.h>
#include<stdbool.h>

bool isVowel(char *c);

int main(){
    char userString[5];
    int i;
    int vowelCount;
    char *c;
        printf("enter string:");
        scanf("%c", userString);
            for(i=0; i<= 4; ++i){
                userString[i] = *c;
                isVowel(c);
                if(isVowel(c)){
                    vowelCount = vowelCount + 1;
                }
            }
    printf("%d\n", vowelCount);
return 0;
}

bool isVowel(char *c){
    if(*c == 'a' || *c == 'A' || *c == 'e' || *c == 'E' || *c == 'i' || *c 
== 'I' || *c == 'o' || *c == 'O' || *c == 'u' || *c == 'U' ){
        return true;
    }
    else{
        return false;
    }
}

I believe that isVowel is always returning false because, when I run it with the input "test!",I get this:我相信 isVowel 总是返回 false 因为,当我使用输入“test!”运行它时,我得到了这个:

enter string: test!
0

You're not setting the c variable.您没有设置c变量。 I suspect this line:我怀疑这一行:

userString[i] = *c;

should be something like:应该是这样的:

c = userString + i;

This is your code with some corrections:这是您的代码,并进行了一些更正:

#include<stdio.h>
#include<string.h>
#include<stdbool.h>

bool isVowel(char c);

int main(){
    char userString[5];
    int i;
    int vowelCount=0;
    char c;
        printf("enter string:");
        scanf("%s", userString); // %s
            for(i=0; i<= 4; ++i){
                c=userString[i] ;              
              printf("%c",c);

                if(isVowel(c)){
                    vowelCount = vowelCount + 1;
                } 
            }
    printf("%d\n", vowelCount);
return 0;
}

bool isVowel(char c){
    return (c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || 
    c == 'I' || c == 'o' || c == 'O' || c == 'u' || c == 'U' ) ; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM