Reputation: 13
I'm trying to do a loop that read from a file a single character until it finds '\n'
or '*'
.
This is the loop that I wrote:
i=0;
do {
fscanf(fin,"%c",&word[i]);
i++;
} while(word[i]!='*'&&word[i]!='\n');
Now I tried to see why it doesn't work with a debugger. When I print word[i]
immediately after the fscanf
it shows me the correct character but then, if I try to print word[i]
while it's doing the comparison with '*'
or '\n'
it shows me that word[i]
is '\000'
and the loop never ends.
I also tried with fgetc
but I have the same error.
Upvotes: 1
Views: 107
Reputation: 4084
Another way:
for(;;) {
int c = fgetc(fin);
if ( c == EOF ) {
break;
word[i] = c;
if( c == '*' || c == '\n' ) {
break;
}
}
Upvotes: 1
Reputation: 7490
You have to make sure that the character you are processing is the same you just read.
Actually you increment counter i
before testing word [i], that's why your check fails.
Try instead
i=0;
do {
fscanf(fin,"%c",&word[i]);
}while(word[i]!='*'&&word[i++]!='\n');
I would rather move the check in the loop (break if the condition is satisfied) leaving in the while check the test on word array length.
Upvotes: 1
Reputation: 780984
Your while
condition is not testing the same element of word
that you just read, because i++
incremented the variable before the test.
Change the test to use word[i-1]
instead of word[i]
to adjust for this.
BTW, word[i] = fgetc(fin);
is a simpler way to read one character.
Upvotes: 0