1

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.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
pingu19
  • 13
  • 3

3 Answers3

1

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.

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
  • 1
    Should there be an `&& (i < word.length)` before the `&&word[i++]!='\n'`, as [suggested by Dan](https://stackoverflow.com/questions/59011511/how-to-read-character-until-a-char-character#comment104271167_59011511)? (I don't know C for the length of an array.) – Andrew Morton Nov 23 '19 at 20:26
  • @Andrew Morton. I agree and I've written it. But I just provided the code according to the known information (word.lenght sounds like a c++ feature, and thi is C) – Roberto Caboni Nov 23 '19 at 20:42
  • 1
    Apparently it would be best if the OP used the length they had set the array to. (For the OP's reference: [How do I determine the size of my array in C?](https://stackoverflow.com/q/37538/1115360).) – Andrew Morton Nov 23 '19 at 20:51
1

Another way:

for(;;) {
   int c = fgetc(fin);
   if ( c == EOF ) {
      break;
   word[i] = c;
   if( c == '*' || c == '\n' ) {
      break;
   }
}
FredK
  • 4,094
  • 1
  • 9
  • 11
  • +1 for a way that doesn't involve any spurious assignments; one might need `i` to do more stuff, (like terminating the string.) – Neil Nov 23 '19 at 21:07
  • 1
    My example is only part of what is needed. It also needs to ensure that word[] is not over-indexed. It should add the terminating NUL only if it is really supposed to be a String, and not just an array of chars. – FredK Nov 23 '19 at 21:10
0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612