2

Here is the code I wrote:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define SIZE 50

int main(int argc, char *argv[])
{
  char str[SIZE];
  char str2[] = "exit";
  //fgets(str, sizeof str, stdin);
  while (strcmp(str, str2) != 0)
  {
    fgets(str, sizeof str, stdin);
    printf("%s", str);
  }
  return 0;
}

But it doesn't seem to exit and is stuck in an infinite loop.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
rohith p
  • 65
  • 7

1 Answers1

4

One solution would be to use:

char str2[]="exit\n";

But a do - while cycle would be best:

int main () {    
    char str[SIZE];
    char str2[]="exit\n";
    do {
        fgets(str, sizeof(str), stdin);
        printf("%s",str);
    } while(strcmp(str,str2));
    return 0; 
}

Since in the first iteration of you cycle str is empty.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
  • 1
    This is probably the most lazy ways imaginable, (and one of the fastest.) I approve. – Neil Feb 13 '20 at 22:38
  • @rohithp, glad to help, extended credits to [Adrian Mole](https://stackoverflow.com/users/10871073/adrian-mole) and [Neil](https://stackoverflow.com/users/2472827/neil) – anastaciu Feb 13 '20 at 22:39