I am trying to create a code in which the person inputs a number N between 1 to 100, so they can input N amount of words-phrases up to 20 characters. The program then finds out if the said word or phrase is a palindrome or not and outputs the answer. I am new to coding in C so I don't know if the code is right or wrong, but everytime i try to input a word-phrase that's more than 8 characters long, or includes a blank space, the program seems to bug out. The first conversion from the array words to the other array sdrow seems to work just fine, but the other seems to be in another world of it's own
#include<stdio.h>
#include<string.h>
int main() {
int N;
int c;
char words[21];
char sdrow[21];
char verify[21];
printf("Please give me a number which constitutes to how many words you would like to type from 1 to 100: ");
scanf("%d", &N);
if(N<=0 || N>100) {
printf("Come on my guy i asked for 1 to 100 not whatever you just typed");
return 1;
}
while (getchar() != '\n');
for(int i = 0; i < N; i++){
printf("Please Type Word %d: " , i+1);
fgets(words, sizeof(words), stdin);
int k = (strlen(words)-2);
c=0;
for(int j=0;j<=k;j++){
if(words[j]==' '){
j++;
}
sdrow[c]=words[j];
c++;
}
printf("%s\n",sdrow);
for(int j=k;j>=0;--j){
verify[k-j]=sdrow[j];
}
printf("%s\n",verify);
int result=strcmp(verify,sdrow);
if(result==0){
printf("Input is a palindrome\n");
}
else{
printf("Input is not a palindrome\n");
}
}
return 0;
}
Successfull Input
1
stats
Successfull Output
stats \\Printing the sdrow array
stats \\Printing the verify array
Input is a palindrome
Unsuccessfull Input
1
never odd or even
Unsuccessfull Output
neveroddoreven \\sdrow array got rid of blank spaces as intended
α \\here's where the "flipped" version of sdrow is supposed to be
Input is not a palindrome
Sometimes the output spurts out garbage , while sometimes it doesn't output anything at all
The Problem seems to be on the reversal of sdrow to verify but i don't know how to fix it. is it just bad coding or is there something else going on? Would you mind taking a little time of your day to help me out?
I've tried using a "middle man" by using a char temp to firs input the values of the sdrow array and then put them to the verify array, but it still doesn't work
Agree -- the problem does seem to be your string reverse method. Here is string reverse code for you, tested and runnable here.
NOTE: this code over-writes the original string, so be sure to save a copy of the original string if you still need it after this runs.
Output:
Putting it all together -- here is a suggested function for using sreverse() in your program -- is_palindrome() -- returns true (1) if reversed string matches original string -- tested, runnable code is here:
Output:
Here is yet another implementation of is_palindrome() inspired by what stackoverflow user einpoklum said -- you don't need to reverse the string.
Yes, it is true. So I put together one more for you...
Tested, runnable code is here
Output: