Search code examples
cinputcharinfinite-loop

How to read character until a char character?


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.


Solution

  • 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.