Reputation: 67
My Code is HERE
int main(){
FILE *fp;
fp = fopen("dic.txt", "r");
while(getc(fp) != EOF){
if(getc(fp) == ' '){
printf("up ");
}
}
}
My dic.txt is HERE
my predict is that "up up up up "
because, there are four space " "
but it printed "up " only one
what is problem?
Upvotes: 0
Views: 125
Reputation: 1
Try Out This Code:
FILE *fp;
fp = fopen("dic.txt", "r");
int ch = getc(fp);
while(ch != EOF){
if(getc(fp) == ' '){
printf("up ");
}
}
return 0;
Upvotes: 0
Reputation: 15525
You are calling getc
twice per iteration of the loop; one of these two calls compares the character to EOF
, while the other call compares the character to ' '
.
This has two consequences:
"up"
for the spaces which are on even position, and will miss all spaces which are on odd position;getc
after reaching EOF
the first time.How to fix
You need to make a single call to getc
per iteration of the loop. Save the character returned by getc
to a local variable; then use this variable to check for spaces in the body of the loop, and to check for EOF
in the condition of the loop.
Upvotes: 3
Reputation: 50881
You want this:
#include <stdio.h>
int main() {
FILE* fp;
fp = fopen("dic.txt", "r");
if (fp == NULL)
{
printf("Can't open file\n");
return 1;
}
int ch; // int is needed her, not char !!
while ((ch = getc(fp)) != EOF) { // read one char and check if it's EOF in one go
if (ch == ' ') {
printf("up ");
}
}
}
getc
once only in the loop, otherwise you skip one out of two characters.fopen
fails.Upvotes: 0