【发布时间】:2021-06-24 00:14:30
【问题描述】:
我必须找出每个字符在字符串链表中重复的次数。字符串被存储并从文件中读取。我必须以两种方式打印结果:字母顺序和增长顺序。
我试图编写一个函数来计算给定字符重复的次数,但它崩溃了。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct list {
char *string;
struct list *next;
};
typedef struct list LIST;
int count(struct list* head, char search) // funct to calculate how many
//times 1 string appears
{
struct list* current = head;
int count=0;
while (current!=NULL)
{
if(current->string == search)
count++;
}
return count;
}
int main(void) {
FILE *fp;
char line[128];
LIST *current, *head;
head = current = NULL;
fp = fopen("test.txt", "r");
while(fgets(line, sizeof(line), fp)){
LIST *node = malloc(sizeof(LIST));
node->string = strdup(line);
node->next =NULL;
if(head == NULL){
current = head = node;
} else {
current = current->next = node;
}
}
fclose(fp);
//test print
for(current = head; current ; current=current->next){
printf("%s", current->string);
}
count(head, "a");
return 0;
}
test.txt 文件包含:
Astazi nu este maine
【问题讨论】:
-
我在
int count函数中的 count++ 之后添加了一行current = current->next;但是当打印出来时,它打印我 0,虽然它应该是 2 -
您的示例依赖于您未与我们共享的 test.txt。我建议您简化示例并对测试数据进行硬编码以演示问题。
-
@AllanWind 刚刚编辑了描述,我已经将 test.txt 中的数据放入其中
-
见this C reference。使用GCC 编译您的C 代码,调用为
gcc -Wall -Wextra -g,改进您的代码以不收到警告,然后使用GDB 调试器了解您的可执行文件的行为。 -
这里的问题是你的代码从编译器发出了几个警告,但你没有在问题中提到它。您应该google这些警告消息并阅读相关的 Stack Overflow 问题甚至在发布您自己的问题之前。
标签: c file linked-list