简体   繁体   中英

Why does my letter counter display 0 when put in a function

I'm very new to C and trying to create a counter for how many times the letter "a" appears in a string. I get it working by putting it directly into main, however when I put it into a function, my printf outputs 0.

#include <stdio.h>
#include <string.h>
#define STRING_LENGTH 50

void letter_counter(char input[STRING_LENGTH], int count, char letter ) {
    int i;
    for (i = 0; i < strlen(input); i++){
    if (input[i] == letter) {
        count++;
}
}
}


int main() {

    int a1 = 0;
    char a = 'a';

    printf("Please write a word\n");

    char input[STRING_LENGTH] = {0};
    fgets(input,STRING_LENGTH,stdin);
    input[strlen(input) - 1] = 0;

    letter_counter(input, a1, a);
    printf("%i\n", a1);




}

You are not returning the value of what you have counted. It looks like you think that a1 is going to contain the total, but it's not.

Your letter_counter function needs to return an int value, not void .

int letter_counter(char input[STRING_LENGTH], char letter ) {
    int i;
    int count = 0;

    for (i = 0; i < strlen(input); i++){
    if (input[i] == letter) {
        count++;
    }

    return count;
}

Then you need to assign the return value of the function to a variable:

a1 = letter_counter(input, a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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