gpt4 book ai didi

c - 我不知道如何将输入文件中的字符串(单词)读取到链接列表中

转载 作者:行者123 更新时间:2023-11-30 17:03:35 25 4
gpt4 key购买 nike

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


struct node
{
char *data;
struct node *next;
};


void insertNode(struct node**, char *);
void printList(struct node*);


int main()
{
struct node *head = NULL;
FILE *fptr;
char file_name[20];
char str[1000];
int numOfChar;


printf("Enter the name of the file: ");
scanf("%s",file_name);


printf("Enter the number of characters per line: ");
scanf("%d",&numOfChar);


fptr=fopen(file_name,"r");
char tokens[100];
while(fgets(str, sizeof(str), fptr) != NULL)
{

while (sscanf(str, "%s", tokens) != EOF)
{

}


}


fclose(fptr);
printList(head);


return 0;
}


void insertNode(struct node** nodeHead, char *data)
{
struct node* new_node = (struct node*) malloc(sizeof(struct node));
struct node *last = *nodeHead;
char *str;


str= (char *)malloc(60*sizeof(char));
strcpy(str, data);


new_node->data = str;
new_node->next = NULL;


if (*nodeHead == NULL)
{
*nodeHead = new_node;
return;
}


while (last->next != NULL)
{
last = last->next;
}


last->next = new_node;
}

我的程序应该将每个单词读入链接列表,但我不知道如何从输入文件中获取每个单词/字符串。输入文件是 ASCII 文本文件。有什么建议么?感谢您的帮助。

void printList(struct node* node)
{
while(node != NULL)
{
printf(" %s ", node->data);
node = node->next;
}
}

最佳答案

例如,您可以使用非常低级别的字符扫描,如下例所示 - 它可能会扩展为实际接受多个分隔符字符、分隔符重复等:

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

int main() {
FILE *fptr;
char buf[100];
char *p, *s;

strcpy(buf, "this is just a test");

fptr=fopen("test.txt","r");
while(fgets(buf, sizeof(buf), fptr) != NULL)
{
printf("LINE: %s\n", buf);
/* scan characters and print tokens - single space is a separator */
p = s = buf;
while(*p!=0) {
if (*p==' ') {
*p = 0;
printf("TOKEN: %s\n", s);
s = p+1;
}
p++;
}
printf("TOKEN: %s\n", s);

}


fclose(fptr);
return 0;
}

调用可能如下所示:

$ cat test.txt
this is test1
this is test2
$ gcc tokens.c && ./a.out
LINE: this is test1

TOKEN: this
TOKEN: is
TOKEN: test1

LINE: this is test2

TOKEN: this
TOKEN: is
TOKEN: test2

关于c - 我不知道如何将输入文件中的字符串(单词)读取到链接列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36109939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com