我正在尝试以CS50 pset2的可读性进行练习,并且试图计算文本中有多少个句子。到目前为止,我的代码是这样的:
#include<stdio.h>
#include<cs50.h>
#include<string.h>
#include<stdbool.h>
#include<ctype.h>
int isdelim(char c, int sentences)
int main (void)
{
string text = get_string("Text: ");
int sentences = 0;
for(int i = 0; i < strlen(text);i++)
{
sentences = isdelim(text[i], sentences);
}
printf("Sentences: %i\n", sentences);
}
int isdelim(char c, int sentences)
{
return c == '.' || c == '!' || c == '?';
sentences++;
}
但是当我执行./readability
并输入文本:Hello, world! Beautiful day!
时,它的输出为:Sentences:0
。
我是C语言的新手,所以我无法真正理解所有这些功能。我尝试搜索网络并使用其他外部资源,但没有任何意义。如果您给我答案,请确保告诉我它为什么起作用,以便我学习。我将来可能需要这些知识。非常感谢。
答案 0 :(得分:4)
有几个问题。
return
语句时,函数结束。此后将不会执行任何操作。因此,sentences++
永远不会执行。sentences
函数中递增isdelim()
不会影响main()
中的变量。int delim(char c, int sentences);
是一个函数声明,而不是一个函数调用。函数调用不包含类型声明。您可以通过使用if
语句来检查条件来解决第一个问题,而不是立即返回条件的结果。
您可以通过将指针传递给变量并取消引用,或者让函数返回新值sentences
来解决第二个问题。
#include<stdio.h>
#include<cs50.h>
#include<string.h>
#include<stdbool.h>
#include<ctype.h>
int isdelim(char c, int sentences);
int main (void)
{
string text = get_string("Text: ");
int sentences = 0;
for(int i = 0; i < strlen(text);i++)
{
sentences = isdelim(text[i], sentences);
}
printf("Sentences: %i\n", sentences);
}
int isdelim(char c, int sentences)
{
if (c == '.' || c == '!' || c == '?') {
sentences++;
}
return sentences;
}
答案 1 :(得分:1)
@Baramar提出了一些优点,但是我认为代码可以使用重构。 isdelim
函数令人困惑。它被命名为布尔函数,因此它应该返回一个bool
。而且该函数不应使用sentences
参数;而是让调用者处理增量。而且我已经自由地在循环之前调用strlen
,因此不会在每次迭代时重新计算它。所以:
#include<stdio.h>
#include<cs50.h>
#include<string.h>
#include<stdbool.h>
#include<ctype.h>
bool isdelim(char c);
int main (void)
{
string text = get_string("Text: ");
int sentences = 0;
int length = strlen(text);
for (int i=0; i<length; i++)
{
if (isdelim(text[i]))
{
sentences++;
}
}
printf("Sentences: %i\n", sentences);
}
bool isdelim(char c)
{
return c == '.' || c == '!' || c == '?';
}