读书人

getc()的用法解决办法

发布时间: 2012-02-04 15:43:08 作者: rapoo

getc()的用法
从下面的paper.txt中读单词,每读到一个单词,就把它保存起来,利用给定的
指针数组
#define MAXWORDS 100
char *words[MAXWORDS];
要用 getc()一个字母,一个字母的读,遇到 ' '(空格)或 '\n '(换行)就把之前读到的算做一个单词.
=====================================================================
/* paper.txt */
This paper describes a network architecture for large-scale, interactive,distributed 3D environments. for this, Its main goals are the maintenance of low latency during user interaction and fast broadcasting techniques in order to fullfill consistency requirements.
=====================================================================
然后把读到的单词记录到单词帐里.但重复的单词只记一次,全部读完后,最后把单词帐里的单词全部输出.




[解决办法]
提供一个参看:

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

#define MAXWORDS 100
int main()
{
char tmp[20]={0}, c;
char *words[MAXWORDS];
int index=0, i=0, m;

FILE *fp=fopen( "paper.txt ", "r ");
while((c=fgetc(fp))!=EOF)
{
if(c== ' ' || c== '\n ')
{
tmp[i]= '\0 ';
i=0;
for(m=0; m <index; m++)
if(strcmp(tmp, words[m]) == 0)break;
if(m <index)continue;

words[index]=(char *)malloc((strlen(tmp)+1)*sizeof(char));
strcpy(words[index++], tmp);
}
else
{
tmp[i++]=c;
}
}

for(i=0; i <index; i++)
puts(words[i]);
system( "pause ");
return 0;
}

读书人网 >C语言

热点推荐