如何让我的代码打印正确的字母数?

How to get my code to print the right letter count?

我写了一些代码来打印出输入到给定文本中所需的字母数。由于某种原因,在 9 个字母后它似乎增加了一个,并且会稍微超过输入中给出的字母数。非常感谢任何建议:)

// Libraries
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <ctype.h>

// Function to count letters
int count_letter(string text)
{
    // Declaring function variables
    int lettercount = 0;
    int number_of_letters;
    int spaces = 0;
    int letter_all;

    // Getting length of the text
    number_of_letters = strlen(text);

    // Counting the letters in the text inputted
    for(lettercount = 0; lettercount < number_of_letters; lettercount++)
       {    // If text is from a-z then count the text
            if(isalpha(text[lettercount]))
                lettercount++;
            // If text is equal to space then add up the spaces
            else if(isspace(text[lettercount]))
                spaces++;
            // Minus the spaces from the lettercount
            letter_all = lettercount - spaces;
        }

    return letter_all;

}


int main(void)
{
    // Getting a string of Text and storing it in a variable
    string passage = get_string("text: ");
    {
        printf("%i letter(s)\n", count_letter(passage));

    }

}

当您执行 letter_all = lettercount - spaces 时,您会将 space 的数量减去字母数量。所以,如果你有字符串 "he llo" 你有 5 个字母和 1 个 space 并且你正在做 5-1。然后你的程序打印 4 这是不正确的。所以,你应该只打印 lettercount 来获取字母数。

这就是您的函数应有的样子。

int count_letter(string text)
{
    // Declaring function variables
    int lettercount = 0;
    int number_of_letters;
    int spaces = 0;
    int letter_all,i;

    // Getting length of the text
    number_of_letters = strlen(text);
    // Counting the letters in the text inputted
    for(i = 0; i < number_of_letters; i++)
       {    // If text is from a-z then count the text
            if(isalpha(text[i]))
                lettercount++;
        }

    return lettercount;

}

在你的函数中你应该删除这一行 letter_all = lettercount - spaces 这将减少实际字母的数量

// Libraries
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <ctype.h>

int count_letter(string text)
{
    // Declaring function variables
    int lettercount = 0;
    int number_of_letters;
    int spaces = 0;
    int letter_all,i;

    // Getting length of the text
    number_of_letters = strlen(text);
    // Counting the letters in the text inputted
    for(i = 0; i < number_of_letters; i++)
       {    // If text is from a-z then count the text
            if(isalpha(text[i]))
                lettercount++;
        }

    return lettercount;

}
int main(void)
{
    // Getting a string of Text and storing it in a variable
    string passage = get_string("text: ");
    {
        printf("%i letter(s)\n", count_letter(passage));

    }

}