我的代码不打印给定文本中的字母数。为什么?
My code does not print numbers of letters in a given text. Why?
我正在尝试创建一个如下所示的函数,该函数将计算输入文本中的字母数并输出一个整数值。我下面的代码可以编译,但不会打印出结果。我错过了什么吗?
// Libraries
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
int count_letter(string text)
{
int lettercount;
int number_of_letters;
number_of_letters = strlen(text);
for(lettercount = 0; lettercount < number_of_letters;)
if (isalpha(number_of_letters))
lettercount++;
return lettercount;
}
int main(void)
{
string text = get_string("text: ");
{
printf("%i letter(s)", count_letter(text));
printf("\n");
}
}
因为 number_of_letters
是一个整数,你认为 isalpha(number_of_letters)
的计算结果是什么?更不用说 for 循环或函数中的 if 周围没有大括号 {}
,这使得代码难以阅读,实际上可能会导致您意想不到的结果。
需要说明的是,这个测试 if (isalpha(number_of_letters))
不正确。由于程序想要计算 text
中字母的字符数,因此测试类似于 if (isalpha(text[lettercount]))
.
我正在尝试创建一个如下所示的函数,该函数将计算输入文本中的字母数并输出一个整数值。我下面的代码可以编译,但不会打印出结果。我错过了什么吗?
// Libraries
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
int count_letter(string text)
{
int lettercount;
int number_of_letters;
number_of_letters = strlen(text);
for(lettercount = 0; lettercount < number_of_letters;)
if (isalpha(number_of_letters))
lettercount++;
return lettercount;
}
int main(void)
{
string text = get_string("text: ");
{
printf("%i letter(s)", count_letter(text));
printf("\n");
}
}
因为 number_of_letters
是一个整数,你认为 isalpha(number_of_letters)
的计算结果是什么?更不用说 for 循环或函数中的 if 周围没有大括号 {}
,这使得代码难以阅读,实际上可能会导致您意想不到的结果。
需要说明的是,这个测试 if (isalpha(number_of_letters))
不正确。由于程序想要计算 text
中字母的字符数,因此测试类似于 if (isalpha(text[lettercount]))
.