Search code examples
cnewlinefgets

c remove new line char help


Im fairly new to c sorry if this is a stupid question!

i have this:

  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question)));
  memq= question;

however the question variable always has a new line on the end of it ! how do i remove this / prevent it happening?

i have tried this:

  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question))-sizeof(char));
  memq= question;

there was no effect!


Solution

  • to get rid of the newline, before your malloc, do :

    question[strlen(question)-1] = 0;
    

    an alternative (suggested in the comments below) would be to do the following instead:

    question[strcspn(question, "\n")] = '\0';
    

    change the malloc line to:

    char *memq = malloc(strlen(question)+1);
    

    change the assignation line:

    memq = question;
    

    to:

    strcpy (memq, question);