0

Im am doing a several exercises to manipulate string and all of them i need to give option for the user repeat the program. But the program only reads my first fgets.
Here goes one example

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(){

  int i;
  char text[150], ch;
  do {
    printf("Enter a text with up to 150 characters");
    fgets(texto, sizeof(texto), stdin);
    printf("\n=== INVERTED TEXT ===\n");
    for(i=strlen(text); i >= 0; i--){
      putchar(texto[i]);
    }
    printf("\n\n Do you wish to repeat the program ?(Y/N).: ");
    fflush(stdin);
    scanf("%c", &ch);
  } while(toupper(ch) == 'Y');

  return 0;
}

In the first loop the programs executes well, but then its doesn't let me input a new value for variable text. Is there an easy way to solve this?

genpfault
  • 51,148
  • 11
  • 85
  • 139
  • 2
    Note that `text[strlen(text)]` is the string terminator. Are you sure you want to print it? – Some programmer dude Nov 04 '20 at 01:50
  • 1
    Also note that passing an input-only stream (like `stdin`) to `fflush` is explicitly mentioned in the C specification as *undefined behavior*. – Some programmer dude Nov 04 '20 at 01:52
  • 2
    `scanf` leaves the newline following the Y/N so `fgets` reads an empty line; dupe https://stackoverflow.com/questions/61642572/using-fgets-after-scanf (6 mos ago) and https://stackoverflow.com/questions/2366509/input-in-c-scanf-before-gets-problem and https://stackoverflow.com/questions/5546874/using-scanf-and-fgets-in-the-same-program (~10 yrs ago) – dave_thompson_085 Nov 04 '20 at 02:28
  • Unless you have a non-conforming compiler (there is one in particular) `fflush(stdin);` doesn't and invokes *Undefined Behavior*. It is only defined for *output* or *update* streams [C11 Standard - 7.21.5.2 The fflush function(p2)](http://port70.net/~nsz/c/c11/n1570.html#7.21.5.2p2) – David C. Rankin Nov 04 '20 at 05:06

0 Answers0