gpt4 book ai didi

c - Strtok 问题 C(EOF 字符?)

转载 作者:行者123 更新时间:2023-11-30 14:26:43 24 4
gpt4 key购买 nike

我尝试编写的代码应该从 txt 文件中读取文本并分成字符串。我得到了以下代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
FILE *fp;
int i=0;
char *words=NULL,*word=NULL,c;
if ((fp=fopen("monologue.txt","r"))==NULL){ /*Where monologue txt is a normal file with plain text*/
printf("Error Opening File\n");
exit(1);}
while ((c = fgetc(fp))!= EOF){
if (c=='\n'){ c = ' '; }
words = (char *)realloc(words, ++i*sizeof(char));
words[i-1]=c;}
word=strtok(words," ");
while(word!= NULL){
printf("%s\n",word);
word = strtok(NULL," ");}
exit(0);
}

问题是我得到的输出不仅是文本(现在作为单独的字符串),而且还有一些字符\r(这是回车符),还有\241\r\002 我无法找到它们是什么?你能帮我一下吗?

最佳答案

主要问题是您永远不会在构建的字符串末尾放置空终止符。

更改:

    while ((c = fgetc(fp))!= EOF){
if (c=='\n'){ c = ' '; }
words = (char *)realloc(words, ++i*sizeof(char));
words[i-1]=c;}
word=strtok(words," ");

致:

    while ((c = fgetc(fp))!= EOF){
if (c=='\n'){ c = ' '; }
++i;
words = (char *)realloc(words, i + 1);
words[i-1]=c;}
words[i] = '\0';
word=strtok(words," ");

关于c - Strtok 问题 C(EOF 字符?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8684741/

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