gpt4 book ai didi

c - fgets 没有得到最后一个字符

转载 作者:行者123 更新时间:2023-12-02 08:38:08 25 4
gpt4 key购买 nike

出于某种原因,当我在以下代码中打印短语时,我发现 fgets 函数没有获取文本文件中的最后一个字符。我已经检查过 mone1 并看到它为文件中的文本提供了足够的空间。有人对这种情况有解释和解决办法吗?

Tnx,迪恩。

ps 我很确定字符串的长度不是问题,因为即使我将其更改为 2 个字符,它仍然只打印第一个字符(不打印最后一个字符),并且全部写在同一行中.

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

int main(int argc, char * argv[])
{
printf("ss");
FILE * sent=NULL;
FILE * voca=NULL;
sent=fopen(argv[1],"r");
voca=fopen(argv[2],"r");
if(voca==NULL){
printf("cannot open voca ");
fclose(voca);
}
if(sent==NULL){
printf("cannot open sent");
fclose(sent);
}
int mone1=0;
int mone2=0;
while(EOF!=fgetc(sent))
mone1++;
while(EOF!=fgetc(voca))
mone2++;
fseek(sent,0L,SEEK_SET);
fseek(voca,0L,SEEK_SET);
char* phrase=(char*)(malloc(mone1*sizeof(char)));
char* voc=(char*)(malloc(mone2*sizeof(char)));
fgets(phrase,mone1,sent);
fgets(voc,mone2,voca);
printf("%s",phrase);
return 0;
}

最佳答案

char *fgets(char * restrict s, int n, FILE * restrict stream);

The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s.



换句话说,如果您需要阅读 mone1字符,传入 n至少 mone1 + 1并确保缓冲区也足够。原因是 fgets将添加尾随 \0在末尾。

关于c - fgets 没有得到最后一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19198861/

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