0

1)我需要从文件中读取字符串并将该字符串转换为链表

所以...如果我读到这个字符串“Some String”

链表将如下所示

节点1-“S”

节点2-“o”

节点3-“m”

节点4-“e”

节点5 - 空

节点6-“S”

节点7-“t”

节点8-“r”

节点9-“我”

节点10-“n”

节点11-“g”

node12 - 空

将为“”(空格)和“\0”空字符发出 NULL

实现这一点的最佳方法是什么..

typedef struct node
{
// each node holds a single character
char data;

// pointer to next node in linked list
struct node *next;
} node;

int i;
char buffer[1032];

    FILE *ifp = fopen("file.txt", "rb");

    //read the first line of file
    fscanf(ifp, "%s", buffer);

node *myList = malloc(sizeof(node));

for(i = 0; i < strlen(buffer); i++)
    /*I DON'T KNOW WHAT TO DO HERE!!!!*/

在这里我迷路了,或者如果我的实施完全错误,请告诉我

4

2 回答 2

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

typedef struct node {
    char data;         // each node holds a single character
    struct node *next; // pointer to next node in linked list
} node;

int
main(int argc, char* argv[]) {
    int i;
    FILE* fp = fopen("example.txt", "r");   
    if (!fp) {
        perror("fopen");
        exit(1);
    }

    node *top = NULL;
    node *cur = NULL;
    int c;
    while ((c = fgetc(fp)) >= 0) {
        node *item = malloc(sizeof(node));
        item->data = c;
        item->next = NULL;
        if (!cur) {
            // first time, store top.
            top = cur = item;
        } else {
            // chain nexts.
            cur->next = item;
            cur = item;
        }
    }
    fclose(fp);

    // print datas
    cur = top;
    while (cur) {
        printf("%c\n", cur->data);
        cur = cur->next;
    }

    // free datas
    cur = top;
    while (cur) {
        node *item = cur->next;
        free(cur);
        cur = item;
    }
    return 0;
}
于 2013-06-27T00:57:59.273 回答
0

fscanf(ifp, "%s", buffer);会在读到“Some”后停止。我使用 fgets() 代替。在手册中(man fgets):

fgets() 从流中最多读入一个小于 size 的字符,并将它们存储到 s 指向的缓冲区中。在 EOF 或换行符后停止读取。如果读取了换行符,则将其存储到缓冲区中。'\0' 存储在缓冲区中的最后一个字符之后。

最后一个 '\0' 便于将缓冲区作为字符串处理。所以我之后的代码FILE *ifp = fopen("file.txt", "rb");是:

fgets(buffer,1032-1,ifp);
node *myList,*head,*pre = NULL;

for(i = 0; buffer[i] != '\0' ; i++) {
    myList = malloc(sizeof(node));
    myList->data = buffer[i];   
    if(pre!=NULL)
        pre->next = myList;
    else
        head = myList;
    pre = myList;
}

while(head!=NULL) {
    printf("%c\n",head->data);
    head=head->next;
}
fclose(ifp);

您的工具将 '\n' 和空间存储为 NULL,当您更改时它可以

myList->data = buffer[i];

if(buffer[i]=='\n' || buffer[i]==' ')
    myList->data = 0;
else
    myList->data = buffer[i];
于 2013-06-27T01:24:18.480 回答