在c代码

时间:2018-04-14 02:47:20

标签: c string struct strcmp

我之前使用过strcmp并且它按预期工作,但在我当前的代码中对我不起作用。

我正在阅读一个名为一群名人的.csv文件。 "Mark Zuckerberg"是触发我的代码最终会做的事情的关键名称(一旦我越过这条路,这与他最近在新闻中所做的事情无关)。我正在使用计数器(queue_size)来计算.csv文件中的行数。我的目标是在strcmp(temp_name, key) == 0时保存计数器的值,但我没有输入if语句,我看不出原因。

密钥在.csv文件中显示为"Mark,Zuckerberg"。我尝试使用strtok来删除逗号。我成功地做到了这一点,但是strcmp()仍然无效(我将关键调整为"MarkZuckerberg")。我还添加memset来清理每次迭代的平板,但这也没有解决问题。

评论该行时,temp_name[strlen(temp_name) - 1] = '\0';似乎也没有改变任何内容。我知道我的struct获取了所有名称,因为printf(我已删除)并且我的print_list函数按预期打印。

我真的需要帮助找出为什么我没有输入if声明 提前感谢任何人提供的任何帮助。

我认为我忽略了一些愚蠢的东西,但我找不到它。

这是我的代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct char_node {
    char name[40];
    struct char_node *next;
} char_node;

typedef struct char_queue {
    char_node *q_head;
    char_node *q_tail;
    int q_size;
} char_queue;

void enqueue(char_queue *q_ptr, char new_name[40]);
//int dequeue(char_queue *q_ptr);
void print_list(char_queue *queue);

int main() {
    int queue_size = 0;
    int m_z_position;
    char_queue queue;
    char temp_name[40];
    char key[] = "Mark,Zuckerberg";

    queue.q_head = NULL;
    queue.q_tail = NULL;
    queue.q_size = 0;

    FILE *file_input;
    file_input = fopen("party.csv", "r");

    memset(temp_name, '\0', sizeof(temp_name));

    while(fgets(temp_name, sizeof(temp_name), file_input)) {
        temp_name[strlen(temp_name) - 1] = '\0';
        if(strcmp(temp_name, key) == 0) {
            printf("test\n");
            m_z_position = queue_size;
        }
        enqueue(&queue, temp_name);
        memset(temp_name, '\0', sizeof(temp_name));
        queue_size++;
    }
    fclose(file_input);

//print_list(&queue);
    printf("m_z_position = %d\n", m_z_position);
    return 0;
}

void enqueue(char_queue *q_ptr, char new_name[40]) {
    char_node *new_node = (char_node*)malloc(sizeof(char_node));
    strcpy(new_node->name, new_name);
    new_node->next = NULL;
    int num;

    if(q_ptr->q_size == 0) {
        q_ptr->q_tail = new_node;
        q_ptr->q_head = new_node;
    } else {
        q_ptr->q_tail->next = new_node;
        q_ptr->q_tail = new_node;
    }
    (q_ptr->q_size)++;
    return;
}

void print_list(char_queue *queue) {
    char_node *temp_list;

    if(queue->q_head != NULL) {
        temp_list = queue->q_head;
        while(temp_list != NULL) {
            printf("%s\n", temp_list->name);
            temp_list = temp_list->next;
        }
    }
    printf("\n");
    return;
}

我无法弄清楚如何添加文件,但这里是.csv文件的内容

Jeff,Bezo
Bill,Gates
Warren,Buffett
Berkshire,Hathaway
Bernard,Arnault
Amancio,Ortega
Carlos,Slim
Charles,Koch
David,Koch
Larry,Ellison
Michael,Bloomberg
Larry,Page
Sergey,Brin
Jim,Walton
S,Robson
Alice,Walton
Ma,Huateng
Francoise,Bettencourt
Mukesh,Ambani
Jack,Ma
Sheldon,Adelson
Steve,Ballmer
Li,Ka-shing
Hui,Ka
Lee,Shau
Wang,Jianlin
Beate,Heister
Phil,Knight
Jorge,Paulo
Francois,Pinault
Georg,Schaeffler
Susanne,Klatten
David,Thomson
Jacqueline,Mars
John,Mars
Joseph,Safra
Giovanni,Ferrero
Dietrich,Mateschitz
Michael,Dell
Masayoshi,Son
Serge,Dassault
Stefan,Quandt
Yang,Huiyan
Paul,Allen
Leonardo,Del
Dieter,Schwarz
Thomas,Peterffy
Theo,Albrecht
Len,Blavatnik
He,Xiangjian
Lui,Che
James,Simons
Henry,Sy
Elon,Musk
Hinduja,family
Tadashi,Yanai
Vladimir,Lisin
Laurene,Powell
Azim,Premji
Alexey,Mordashov
Lee,Kun-Hee
Lakshmi,Mittal
Wang,Wei
Leonid,Mikhelson
Charoen,Sirivadhanabhakdi
Pallonji,Mistry
Ray,Dalio
Takemitsu,Takizaki
William,Ding
R,Budi
Gina,Rinehart
German,Larrea
Carl,Icahn
Stefan,Persson
Michael,Hartono
Joseph,Lau
Thomas,A
Vagit,Alekperov
James,Ratcliffe
Donald,Bren
Iris,Fontbona
Gennady,Timchenko
Abigail,Johnson
Vladimir,Potanin
Lukas,Walton
Charlene,de
Zhang,Zhidong
Petr,Kellner
Andrey,Melnichenko
David,A
Klaus-Michael,Kuehne
Li,Shufu
Mikhail,Fridman
Rupert,Murdoch
Dhanin,Chearavanont
Robert,Kuok
Emmanuel,Besnier
Shiv,Nadar
Viktor,Vekselberg
Aliko,Dangote
Harold,Hamm
Steve,Cohen
Dustin,Moskovitz
Marcel,Herrmann
Reinhold,Wuerth
Charles,Ergen
Eric,Schmidt
Philip,Anschutz
Jim,Kennedy
Blair,Parry-Okeden
Alain,Wertheimer
Gerard,Wertheimer
Leonard,Lauder
Heinz,Hermann
Dilip,Shanghvi
Hasso,Plattner
Stephen,Schwarzman
Lei,Jun
Hans,Rausing
Alisher,Usmanov
Donald,Newhouse
Peter,Woo
Luis,Carlos
Robin,Li
Carlos,Alberto
Seo,Jung-Jin
Kumar,Birla
Alexander,Otto
Stefano,Pessina
Udo,A
Wang,Wenyin
Andrew,Beal
Lee,Man
John,Menard
Xu,Shihui
Zhou,Hongyi
Gong,Hongjia
Michael,Otto
David,Tepper
Roman,Abramovich
Liu,Qiangdong
Robert,A
Alberto,Bailleres
Uday,Kotak
Pierre,Omidyar
Walter,PJ
Dietmar,Hopp
Graeme,Hart
Eduardo,Saverin
Yan,Zhi
Radhakishan,Damani
German,Khan
Ronald,Perelman
Gautam,Adani
Micky,Arison
Pan,Zhengmin
Joseph,Tsai
Thomas,Frist
Mikhail,Prokhorov
Galen,Weston
Zong,Qinghou
Eyal,Ofer
Charles,Schwab
Gianluigi,A
Herbert,Kohler
Viktor,Rashnikov
Harry,Triguboff
August,von
Yao,Zhenhua
Jan,Koum
Cyrus,Poonawalla
James,Goodnight
Ken,Griffin
Giorgio,Armani
Ernesto,Bertarelli
Savitri,Jindal
Sunil,Mittal
James,Chambers
Katharine,Rayner
Margaretta,Taylor
Terry,Gou
Gordon,Moore
James,Irving
Stanley,Kroenke
Melker,Schorling
Johann,Graf
Guo,Guangchang
John,Malone
Xavier,Niel
Silvio,Berlusconi
Carl,Cook
David,Geffen
Hui,Wing
Walter,Kwok
George,Soros
Edward,Johnson
Massimiliana,Landini
David,Duffield
George,Kaiser
Patrick,Soon-Shiong
Zhou,Qunfei
Nicky,Oppenheimer
Sun,Piaoyang
Wu,Yajun
Alexei,Kuzmichev
Stephen,Ross
Vincent,Bollore
Pauline,MacMillan
Jay,Y
Anders,Holch
Eli,Broad
Michael,Kadoorie
Iskander,Makhmudov
Frederik,Paulsen
Sun,Hongbin
Christy,Walton
Shahid,Khan
Ananda,Krishnan
Carrie,Perrodo
Quek,Leng
Wang,Wenxue
John,Doerr
Patrick,Drahi
Eva,Gonda
Willi,A
Ricardo,Salinas
Suh,Kyung-Bae
Pollyanna,Chu
John,Fredriksen
Goh,Cheng
Sri,Prakash
Lu,Zhiqiang
Jorn,Rausing
Johann,Rupert
Jacques,Saade
Wu,Shaoxun
Leonid,Fedun
Kim,Jung-Ju
Sandra,Ortega
Jim,Pattison
Michael,Platt
Chan,Laiwa
David,Green
Hank,A
Dmitry,Rybolovlev
Tsai,Eng-Meng
Andreas,von
Oleg,Deripaska
Liu,Yongxing
Ludwig,Merckle
Brian,Acton
John,Grayken
Ann,Walton
Augusto,A
Finn,Rausing
Mark,Zuckerberg
Kirsten,Rausing
Odd,Reitan
Nassef,Sawiris
Wee,Cho
Aloys,Wobben
Leon,Black
Ivan,Glasenberg
John,Paulson
Wei,Jianjun
Francis,Choi
Erivan,Haub
Jason,Jiang
Suleiman,Kerimov
Ian,A
Pang,Kang
David,Shaw
Kushal,Pal
John,A
Acharya,Balkrishna
Guenther,Fielmann
Daniel,Gilbert
Antonia,Johnson
Vikram,Lal
Akira,Mori
Maria-Elisabeth,Schaeffler-Thumann
Albert,Frere
Richard,Kinder
Robert,Kraft
Ralph,Lauren
Bruno,Schroder
Nusli,Wadia
Pierre,Bellon
Les,Wexner
Benu,Gopal
David,Cheriton
Ma,Jianrong
Whitney,MacMillan
Dan,Olsson
Vivek,Chaand
Teh,Hong
Abdulla,bin
Maria,Asuncion
Ralph,Dommermuth
Frank,Lowy
Wolfgang,Marguerre
Marijke,Mars
Pamela,Mars
Valerie,Mars
Victoria,Mars
David,A
John,Gokongwei
Kwon,Hyuk-Bin
Nancy,Walton
Lin,Yu-Ling
Tom,A
Robert,Rowling
Dennis,Washington
Yao,Liangsong
Zhang,Jindong
Juan,Francisco
David,Sun
John,Tu
Martin,Viessmann
Stef,Wertheimer
Hansjoerg,Wyss
James,Dyson
Laurence,Graff
Jen-Hsun,Huang
Charles,Johnson
Jerry,Jones
Kei,Hoi
Kwee,family
Lee,Shin
Richard,LeFrak
Shigenobu,Nagamori
Steven,Rales
Friede,Springer
Yeung,Kin-man
Rinat,Akhmetov
Shari,Arison
Dannine,Avara
Rahel,Blocher
Andrew,Currie
Scott,Duncan
Milane,Frantz
Diane,Hendricks
Magdalena,Martullo-Blocher
Hiroshi,Mikitani
Gabe,Newell
Pan,Sutong
Anthony,Pratt
John,Reece
Randa,Williams
Zhang,Bangxin

2 个答案:

答案 0 :(得分:1)

我正在修改您的代码,但由于this评论已经说明,您的文件使用"\r\n"作为结束行代码,可以在阅读后立即使用str[strcspn(str, "\r\n")] = '\0';修复。

但是,这里是代码实现的另一个例子:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct char_node {
    struct char_node *next;
    char name[];
} char_node;

typedef struct char_queue {
    char_node *q_head;
    char_node *q_tail;
    size_t q_size;
} char_queue;

char_node *enqueue(char_queue *q_ptr, char const *new_name);
void print_list(char_queue const *queue);

int main(void) {
    char_queue queue = { .q_head = NULL, .q_tail = NULL, .q_size = 0 };
    char const key[] = "Mark,Zuckerberg";

    FILE *file_input = fopen("party.csv", "r");
    if (file_input == NULL) {
        file_input = stdin;
    }
    char str[40];
    size_t m_z_position = 0;
    while (fgets(str, sizeof str, file_input)) {
        str[strcspn(str, "\r\n")] = '\0';
        if (strcmp(str, key) == 0) {
            m_z_position = queue.q_size;
        }
        enqueue(&queue, str);
    }
    fclose(file_input);

    print_list(&queue);
    printf("m_z_position = %zu\n", m_z_position);
}

char_node *enqueue(char_queue *q_ptr, char const *name) {
    size_t i = strlen(name) + 1;
    char_node *node = malloc(sizeof *node + i);
    if (!node) {
        return NULL;
    }
    strcpy(node->name, name);
    node->next = NULL;

    if (q_ptr->q_size++ == 0) {
        q_ptr->q_tail = q_ptr->q_head = node;
    } else {
        q_ptr->q_tail = q_ptr->q_tail->next = node;
    }
    return node;
}

void print_list(char_queue const *queue) {
    for (char_node const *list = queue->q_head; list; list = list->next) {
        printf("%s\n", list->name);
    }
    printf("\n");
}

答案 1 :(得分:-1)

我担心.csv文件包含"Mark,Zuckerberg"而不是Mark,Zuckerberg

if(strcmp(temp_name, key) == 0){密钥与temp_name进行比较。 这里的关键是Mark,Zuckerberg

  

int strcmp(const char * s1,const char * s2);

     

strcmp()和strncmp()   函数返回大于,等于或小于0的整数,   根据字符串s1大于,等于或小于   string s2。

如果temp_name为"Mark,Zuckerberg",则strcmp将返回正数,因为它包含额外的2个字符,如果temp_name为Mark,Zuckerberg则为0,因为此处的关键字为Mark,Zuckerberg