0

I have written a program that checks if a 6-letter word is a palindrome or not. The code for it is given below:

    #include <stdio.h>
int main()
{
    char l1, l2, l3, l4, l5, l6;
 
    printf("Enter a 6-letter word\n");
 
    scanf("%c", &l1);
    scanf("%c", &l2);
    scanf("%c", &l3);
    scanf("%c", &l4);
    scanf("%c", &l5);
    scanf("%c", &l6);
 
    printf("Let's see if this word is a palindrome. The reversed word is: %c%c%c%c%c%c", l6, l5, l4, l3, l2, l1);
    return 0;
}

However, when I run the code, although I included 6 scanf functions to obtain the 6 letters as input, the program only takes three letters and reverses them, and the rest I am not able to give as input.

Can somebody help me with this one?

  • Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). Place a space in front of `%`, so it's `scanf(" %c", &l6);` – Weather Vane Nov 16 '21 at 09:37
  • Most of the format specifiers for `scanf` automatically filter leading whitespace, but `%c` and `%[]` and `%n` do not. Adding a space in front of the `%` instructs `scanf` to filter leading whitespace here too. – Weather Vane Nov 16 '21 at 09:38
  • 1
    Use `fgets` for user input – klutt Nov 16 '21 at 09:39
  • ...and remember to remove the newline. Every which way, the newline you enter appears in the input. Probably the most FAQ among learners. – Weather Vane Nov 16 '21 at 09:39
  • OT: this is the wrong approach. You need an array for this. What if you want 7 letter words, or 20 letter words? – Jabberwocky Nov 16 '21 at 09:40
  • Thank you everyone for responding... I have recently started learning C Language so I don't yet write codes that are precise. Your replies have helped me in knowing my mistake... – Kausthubha RS Nov 17 '21 at 12:36

0 Answers0