Hello. I have a problem with a code I have created to decide if an input string is a palindrome or not (word is the same if read in wrong direction). The actual code in itself works as intended, however when I tried to put a loop on the whole code it started acting weird.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define STRING_MAX 100
int isPalindrome();
char* removeNonAlpha();
char* strLowerCase();
int main()
{
int x = 0;
char inputString[STRING_MAX];
char cont='y';
do
{
printf("Hello. Please enter a word or sentence: ");
fgets(inputString, STRING_MAX, stdin);
printf("You entered: %s\n", inputString);
//Remove all non alphabetical symbols from the string
removeNonAlpha(inputString);
printf("First we have to remove everything non-alphabetical: %s\n", inputString);
//Make sure all the alphabetical symbols are lower case
strLowerCase(inputString);
printf("Then we have to make everything lower-case: %s\n", inputString);
//After that, check if the string is a palindrome
x = isPalindrome(inputString);
if(x)
{
printf("The string you entered is a palindrome! :D\n");
}
else
{
printf("The string you entered is not a palindrome... :|\n");
}
printf("Would you like to enter another word or sentence? (y/n): ");
cont = getchar();
inputString[strlen(inputString)-1] = '\0';
} while (cont == 'y');
return 0;
}
int isPalindrome(char inputString[])
{
int l = 0, r = strlen(inputString) - 1;
if (l == r)
return 1;
while (r > l)
{
if (inputString[l++] != inputString[r--])
return 0;
}
return 1;
}
char* removeNonAlpha(char inputString[])
{
int i, j;
for(i=0,j=0; i<strlen(inputString); i++,j++)
{
if (isalpha(inputString[i]))
inputString[j] = inputString[i];
else
j--;
}
inputString[j] = '\0';
return inputString;
}
char* strLowerCase(char inputString[])
{
int i;
for(i=0; i<strlen(inputString); i++)
inputString[i] = tolower(inputString[i]);
return inputString;
}
So what I expected was the code to run again and ask for another string to be entered, however it doesn't. I read around a bit about this and it looks like what is happening is what a newline (\n) is still in the input buffer and the fgets is skipped. I tried using a getchar() after the fgets to consume eventual newlines but it did not solve my problem. This is the output I am getting:
Any ideas on how to solve this? I am new to programming and I would love to hear on how I could improve my code generally, although my main concern right now is fixing this loop issue.
EDIT: The only function from string.h that I am allowed to use is strlen().