我正在学习哈佛的cs50x课程,我一直刻意避免使用他们的cs50.h库,这样我就不会因为重新学习如何用C编写某些代码而陷入另一个困境.
以下是我的代码:
int main(void){
// Prompt to enter text & allocate memory for string of 100 char
char *text = malloc(100 * sizeof(char));
printf("Enter Text: ");
fgets(text, 100, stdin);
// Calculate index
int number_of_words = countWords(text);
int number_of_letters = countLetters(text);
int number_of_sentences = countSentences(text);
float L = (float) number_of_letters / number_of_words * 100.0;
float S = (float) number_of_sentences / number_of_words * 100.0;
float index = 0.0588 * L - 0.296 * S - 15.8;
// Print index from if > 1 "less than 1" and if greater that 16 "16+" else print index
if (index < 1){
printf("Reading Level: Before Grade 1\n");
}
else if (index > 16){
printf("Reading Level: Grade 16+\n");
}
else{
printf("Reading Level: Grade %i\n", index);
}
// Free memory and terminate program
free(text);
return 0;
}
// Count functions use a while loop to iterate through each char and count then return total count as int
// Removed due to Stack Overflow saying i have too much code in post
它的目的是从用户那里获得字符串形式的输入,然后解析该信息以提供阅读级别.
**问题:** 我能够在cs50.dev上运行和调试这段代码,它似乎完全按照我的预期工作.Main()的第一行设置文本变量,如下图所示:
text: 0x55ed3e7412a0 "" / *text: 0 '\000'个
但是,try 在我的本地Windows机器上运行/调试会导致文本变量设置如下:
text: 0x7416e0 "\r\r\r\r\r..." / *text: 13 '\r'个
我不明白为什么会发生这种情况,我甚至不确定从哪里开始寻找.显然,它与Malloc()函数有关,但我不明白它可能分配的内容与它在cs50.dev上分配的内容不同.
我想这可能是我的VScode设置有问题,或者可能是我的MinGW设置有问题?这里的任何帮助都是非常感谢的.任何关于如何改进我的代码以及其他意见,将不胜感激.