【发布时间】:2021-12-31 06:00:20
【问题描述】:
我不知道我的代码有什么问题。当我运行它时 (get_string("Text: ");) 不会接受任何东西,我必须 ctrl c 才能摆脱它。我是初学者,这是我第二次用 C 编码,所以请告诉我是否遗漏了一些重要的东西。另外,如果您有任何提示可以使我的代码看起来更好,谢谢!
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
int letters(string a)
float words(string b)
int sentences(string c)
int main(void)
{
// Prompt user
string text = get_string("Text: ");
//L is the average number of letters per 100 words in the text
float L = (letters(text) / words(text)) * 100;
//S is the average number of sentences per 100 words in the text
float S = (sentences(text) / words(text)) * 100;
float index = 0.0588 * L - 0.296 * S - 15.8;
//int grade = index round
int grade = (index);
//printing out grade level
if (grade < 1)
{
printf("Before Grade 1");
}
else if (grade > 16)
{
printf("Grade 16+");
}
else
{
printf("Grade %i\n", grade);
}
}
//letters function that counts letters in string text
int letters(string a)
{
int lettercount = 0;
for(int i = 0, n = strlen(a); i < n; i++)
{
if (isalpha(a[i]))
{
lettercount++;
}
}
return lettercount;
}
//words function that counts spaces in string text
float words(string b)
{
int wordcount = 1;
for(int i = 0, n = strlen(b); i < n; i++)
{
if (isspace(b[i]))
{
wordcount++;
}
}
return wordcount;
}
//sentences function that counts exclamation points and full stops in string text
int sentences(string c)
{
int sentencecount = 0;
for(int i = 0, n = strlen(c); i < n; i++)
{
while ((c[i] == '.') || (c[i] == '!') || (c[i] == '?'))
{
sentencecount++;
}
}
return sentencecount;
}
【问题讨论】:
-
错字:
int letters(string a)-->int letters(string a);你错过了所有原型中的分号 -
"当我运行它时..." 好吧,你不能运行这段代码,因为它不能编译。您是否发布了错误的代码?还是您的系统(编译器、IDE 等)要求您在编译器错误后按 ctrl-c?
-
除了需要正确终止
letters()、words()和sentences()的函数原型之外,如果没有get_string()的函数定义,我们将无法为您提供帮助。 -
@JamesMcPherson 在 CS50 中,
string是typedef的char *和get_string (const string prompt);将读取并分配输入,返回指向已分配字符串的指针。见CS50 on github(实际上是get_string (va_list *args, const char *format, ...)——但出于所有实际目的——它将提示作为第一个参数)。 -
不是计算字符串的长度并使用
for(int i = 0, n = strlen(a); i < n; i++) {...}进行迭代,而是写for(int i=0; a[i]; i++)更习惯。写for( ; *a; a++)就更地道了