Strtok 问题 C(EOF 字符?)
我试图编写的代码应该从 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
主要问题是您永远不会在构建的字符串末尾放置空终止符。
更改:
至:
The main problem is that you never place a null terminator at the end of the string you build up.
Change:
To: