gpt4 book ai didi

c - 我在 C 语言中读取 .txt 文件中的单词时遇到一些问题

转载 作者:行者123 更新时间:2023-11-30 19:52:12 25 4
gpt4 key购买 nike

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

#define WORD_LENGHT 30

typedef struct numnode
{
char* dataPtr;
struct numnode* next;

} NUMNODE;

typedef struct num
{
NUMNODE* head;

} NUM;
//////
//////
//////
int main()
{
char *wp;
char word[80];
int total=0;
FILE *test= fopen("book.txt", "r");
while (fscanf (test, "%s",word) == 1)
{
//printf("%s\n",word); //counting how many words in a book.txt
total++;
}

if (total==0)
{
printf("File not found\n"); //if no word, then return
return;
}

NUM* dic;
dic=(NUM*)malloc(sizeof(NUM)*total);
NUMNODE* temp;
temp=dic->head;

FILE*file = fopen("book.txt", "r");
while(!feof(file))
{
wp=malloc(100);
printf("test1\n");
fscanf(file,"%s",wp);
strcpy(temp->dataPtr,wp); //strcpy is the error part
printf("test2\n");
temp=temp->next;
}
return;
}

this c code read word by word from book.txt and put them to linked list. i got some issues with !feof(file) part.Couldnt figure out what to do.i think strcpy in this loop is the reason of this issue.im waiting for your helps :3

最佳答案

错误是因为结构体成员dataPtr是一个指针,而不是一个数组。所以 strcpy 调用

strcpy(temp->dataPtr,wp);

是错误的,因为它访问非法内存,调用未定义的行为。你需要的是

typedef struct numnode
{
char dataPtr[100]; // dataPtr changed to an array type
struct numnode* next;

} NUMNODE;

请注意,dataPtr 必须至少为 wp 指向的缓冲区的大小。

关于c - 我在 C 语言中读取 .txt 文件中的单词时遇到一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23847806/

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