我有一个程序必须从文件中获取最长的句子。 为实现这一点,我将第一个句子放在一个数组中,然后将 future 的句子与当前最大句子的大小进行比较。
然而,比较两个数组的行为让我望而却步。 该数组的 current_sentence 和 longest_sentence 都是 80 个字符长,但我想知道哪个实际上包含最长的句子(最长可达 80 个字符)。
我已经尝试过许多不同的解决方案(通过谷歌,其中大部分是 stackoverflow 结果)但每次尝试时返回的值都是文件中的第一句话,这让我相信要么检查本身完全失败,或者两个数组的长度都返回为 80。
这些尝试包括(但不限于):
if((sizeof(current_sentence) / sizeof(char)) < (sizeof(longest_sentence) / sizeof(char))
if(sizeof(current_sentence) / sizeof(current_sentence[0])) < (sizeof(longest_sentence) / sizeof(longest_sentence[0]))
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *langste_regel(char *);
int main(void) {
/*
* stdout and stderr required for proper output
*/
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
char *s = langste_regel("vb1.txt");
if(s != NULL) {
printf("\nde langste regel is: %s\n", s);
free(s);
}
return 0;
}
char *langste_regel(char *filename) {
FILE *file;
file = fopen(filename, "r");
if(file == NULL) {
fprintf(stderr, "Kan bestand niet %s openen", filename);
}
char current_sentence[80];
int len = 2;
char *longest_sentence = (char *)malloc(sizeof(char) * len);
fgets(longest_sentence, 80, file);
while(fgets(current_sentence, 80, file)) {
if(sizeof(current_sentence) < sizeof(longest_sentence)) {
strncpy(longest_sentence, current_sentence, 80);
}
}
fclose(file);
return longest_sentence;
}
最佳答案
您想使用 strlen()
来获取行的长度,而不是 sizeof
返回对象占用的字节数。
改变
if(sizeof(current_sentence) < sizeof(longest_sentence)) {
到
if(strlen(current_sentence) < strlen(longest_sentence)) {
我看到的另一个问题是您只分配了 2 个字节,但在这里读取了多达 80 个字节:
char *longest_sentence = (char *)malloc(sizeof(char) * len);
fgets(longest_sentence, 80, file);
关于代码不断崩溃(第 4.2 周已停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30308537/