嗨,我是C编程的初学者。 我编写了一个代码,该代码从输入文件中获取内容以创建链接列表。 因此,所有名称都链接在一起。 汤姆与杰克有联系,依此类推。 输入文件:
tom
jack
tom
mark
tom
jake
我编写了一个计算发生次数的函数,但是无论我如何尝试不断得到警告,tom
的计数始终为0
。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 50
typedef struct node {
char name[MAXN];
struct node *next;
}
node;
int count( node* head, char search_for)
{
node* current = head;
int count = 0;
while (current != NULL)
{
if (current->name== search_for)
count++;
current = current->next;
}
return count;
}
int main (int argc, char **argv) {
FILE *file = argc > 1 ? fopen (argv[1], "r") : stdin;
if (file == NULL)
return 1;
char buf[MAXN];
node *first = NULL, *last = NULL;
while (fgets (buf, MAXN, file)) {
node *head = malloc (sizeof(node));
if (head == NULL) {
perror ("malloc-node");
return 1;
}
buf[strcspn(buf, "\n")] = 0;
strcpy (head->name, buf);
head->next = NULL;
if (!last)
first = last = head;
else {
last->next = head;
last = head;
}
}
if (file != stdin)
fclose(file);
node *ptr = first;
printf("count of tom is %d", count(ptr->name, 't'));
return 0;
}
答案 0 :(得分:0)
您不能将两个带有==的字符数组进行比较。而是必须使用strcmp()函数。第一个(或第二个,顺序无关紧要)必须是链接列表中当前节点的名称,另一个是您要传递给函数(search_for)的参数。如果它们相同,则strcmp()将返回0,在这种情况下,您将增加计数变量。
答案 1 :(得分:0)
您的代码中有一些错误。
这是您代码的有效版本。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 50
typedef struct node {
char name[MAXN];
struct node *next;
}
node;
int count( node* head, char * search_for) //Char * search_for instead of char search_for
{
node* current = head;
int count = 0;
while (current != NULL)
{
if (strcmp(current->name,search_for) == 0) { //using strcmp instead of ==
count++;
}
current = current->next;
}
return count;
}
int main (int argc, char **argv) {
FILE *file = argc > 1 ? fopen (argv[1], "r") : stdin;
if (file == NULL)
return 1;
char buf[MAXN];
node *first = NULL, *last = NULL;
while (fgets (buf, MAXN, file)) {
node *head = malloc (sizeof(node));
if (head == NULL) {
perror ("malloc-node");
return 1;
}
buf[strcspn(buf, "\n")] = 0;
strcpy (head->name, buf);
head->next = NULL;
if (!last)
first = last = head;
else {
last->next = head;
last = head;
}
}
if (file != stdin) fclose(file);
node *ptr = first;
printf("count of tom is %d", count(ptr, "tom")); // ptr instead of ptr->name and "tom" instead of 'tom'
return 0;
}