简体   繁体   English

为什么我的字母计数器在放入 function 时显示 0

[英]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.我是 C 的新手,我正在尝试为字母“a”在字符串中出现的次数创建一个计数器。 I get it working by putting it directly into main, however when I put it into a function, my printf outputs 0.我通过将它直接放入 main 使其工作,但是当我将它放入 function 时,我的 printf 输出 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.看起来您认为a1将包含总数,但事实并非如此。

Your letter_counter function needs to return an int value, not void .您的letter_counter function 需要返回一个int值,而不是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:然后你需要将 function 的返回值赋给一个变量:

a1 = letter_counter(input, a);

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

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