dimanche 25 octobre 2020

Why doesn't 'break' work inside do-while loop? [closed]

I know there have been many questions of this type, but this is not "yet another rookie mistake". Consider the following code snippet:

  do
    {
      c = fgetc (fp);
      line[i++] = c;
      printf ("Character c: %c\n", c);
      printf ("Index i: %d\n", i);
      printf ("Condition: %d\n", (c != '\n'));
      usleep (1 * 1000000);
    }
  while (c != '\n');

I'm reading from a file and want to break at the first newline character. The break never happens, though, even if it is clearly printed that "Condition: 0" when the newline character comes. Even weirder : when I add "exit (0);" after the loop, it works correctly. This doesn't work either:

  do
    {
      c = fgetc (fp);
      line[i++] = c;
      printf ("Character c: %c\n", c);
      printf ("Index i: %d\n", i);
      printf ("Condition: %d\n", (c != '\n'));
      if (c == '\n')
        break;
      usleep (1 * 1000000);
    }
  while (c != '\n');

The code : here. To reproduce, compile, use argument "--add PATH" (replace 'PATH' with an existing path from your system) to create the file and then "--export".

Aucun commentaire:

Enregistrer un commentaire