I'm a beginner with C but am trying to make a script which reads input and, ignoring special characters and spaces, outputs the reverse of the input whether or not the letters make a palindrome.
I've tried tweaking the length of the loop in the fix function as I think that's where the issue is but from what I can tell, strlen() is working as expected, the loop is just stopping when it encounters a space.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 1000 /* The maximum number of characters in a line of
input
*/
void fix(char str[], char str2[]);
int main()
{
char text[MAX], text2[MAX], text3[MAX], text4[MAX], temp;
int i, j;
int length;
puts("Type some text (then ENTER):");
/* Save typed characters in text[]: */
fgets(text, MAX, stdin);
length = strlen(text) - 1;
strcpy(text2, text);
i = 0;
j = length-1;
while(i < j){
temp = text[i];
text[i] = text[j];
text[j] = temp;
i++;
j--;
}
/* Analyse contents of text[]: */
printf("Your input in reverse is:\n");
printf("%s", text);
fix(text, text3);
printf("%s\n", text3);
fix(text2, text4);
printf("%s\n", text4);
if(strcmp(text4, text3) == 0)
printf("Found a palindrome!\n");
return 0;
}
void fix(char str[], char str2[]){
int i;
for(i = 0; i < strlen(str)-1; i+=1){
if (isalpha(str[i])){
str2[i] = tolower(str[i]);
}
}
}
For an input of "Nurses, run", the reversed string outputs correctly, but there is no output of "Found a palindrome!"
Printing text 3 and 4 prints "nur" and "nurses," respectively.
It seems the loop stops when it encounters a space but I can't figure out why as it should go based on the length of the full input.