Strtok 问题 C(EOF 字符?)

发布于 2024-12-23 16:13:21 字数 788 浏览 0 评论 0原文

我试图编写的代码应该从 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我不知道它们是什么?你能帮我一下吗?

the code that i am trying to write is supposed to read text from a txt file and separate into strings. I have come to the following code:

#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);
}

The problem is that the output that i get is not only the text (now as separate strings) but also some characters that are \r(which is carriage return) but also \241\r\002 that i cant find out what they are? Can you help me out?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何以笙箫默 2024-12-30 16:13:21

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

更改:

    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," ");

The main problem is that you never place a null terminator at the end of the string you build up.

Change:

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

To:

    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," ");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文