问题
Hi. I need to read several files without empty lines between words.They can have different layouts, such as 1.txt or 2.txt:
1.txt:
treg
hreger
ig
srg
fre
ig
lre
eg
2.txt:
lregreg
igregr
kreggerg
ereherh
tershs
hsehsteh
asreh
treshse
How do i do that ? How can I count the number of words in the fastest way? I just have the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
FILE *fp;
char palavra[50]="/0";
char *s;
fp = fopen("1.txt","r");
if(fp == NULL){
puts("Open file failed\n");
exit(-1);
}
while(fscanf(fp,"%s",palavra)!=EOF){
s=palavra;
/*do things with s var*/
}
fclose(fp);
exit(0);
}
how i implement something like that:
while ((c = fgetc(fp)) != EOF) {
if (isspace(c)){
continue;
}
回答1:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
enum status { OUT, IN };
int main(){
FILE *fp;
int ch, wc = 0, stat = OUT;
if(NULL==(fp = fopen("1.txt","r"))){
fprintf(stderr, "Open file failed\n");
exit(-1);
}
while(EOF!=(ch=fgetc(fp))){
if(isspace(ch)){
stat = OUT;
} else {
if(stat == OUT){
stat = IN;
++wc;
}
}
}
fclose(fp);
printf("number of words is %d.\n", wc);
return 0;
}
来源:https://stackoverflow.com/questions/23498148/read-words-not-char-from-file-without-empty-lines-in-c-not-duplicated