Search code examples
ctokenfgets

Remove trailing newline character using fgets


I am making a program to read a file and determine if a word is a palindrome. I am running into an issue where the last token has a trailing newline and won't register as a palindrome.

Here is the file input:

leVel CompUtER Science theORY radar

And this is my code:

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

void palindrome(char str[]){
  int length = strlen(str);
  int i = 0;
  int j = length - 1;
  for(i = 0; i < length; i++){
    if(str[i] != str[j]){
      printf("String %s is not a palindrome.\n", str);
      return;
    }
    j--;
  }
  printf("String %s is a palindrome.\n", str);
  return;
}



int main() {

  char line1[100];
  fgets(line1, 100, stdin);
  printf("%s", line1);

  char *token;
  token = strtok(line1, " ");

  while(token != NULL){
    printf("%s\n", token);
    palindrome(token);

    token = strtok(NULL, " ");
  }

Thanks for the help!


Solution

  • If you are using strtok, then you can use " \n" as the delimiter and the newline will be taken care of.

    int main() {
    
      char line1[100];
      fgets(line1, 100, stdin);
      printf("%s", line1);
    
      const char *delim = " \n";
    
      char *token;
      token = strtok(line1, delim);
    
      while(token != NULL){
        printf("%s\n", token);
        palindrome(token);
    
        token = strtok(NULL, delim);
      }
    
      ...
    
    }
    

    Another great method to remove the newline is to use strcspn like this:

    char line[1024];
    fgets(line, sizeof line, stdin);
    
    line[strcspn(line, "\n")] = 0; // removing newline if one is found