Question
In the C program below, I have it to check a text file to check if it is a palindrome. However, my program will not
In the C program below, I have it to check a text file to check if it is a palindrome. However, my program will not ignore spaces and non-alpha characeters in the file. for example " never odd or even!" is a palindrome, but this program considers the spaces and the ! as characters. Can you help fix this program?
#include
void modtext(char line[]); int isPalindrome(char line[]);
int main(int argc, char *argv[]) {
if(argc!=2) { //Error if not filename is entered ****************** printf("Please enter filename after %s ", argv[0]); return -1; } //To open my file ******************************** FILE *fp; fp = fopen(argv[1], "r");
if(fp==NULL){ printf("Unable to open file "); return -1; } //To create the two output files that my program writes to****** FILE *fPal = fopen("palindromeOut.txt", "w"); FILE *fQuote = fopen("quotesOut.txt", "w");
char line[1000];
while(!feof(fp)) { fscanf(fp, " %[^ ]s", line); modtext(line); int isPal = isPalindrome(line); line[0] = toupper(line[0]);
if(isPal){ //To print to palindromeOut.txt *************** fprintf(fPal, "%s ", line); //To print to screen ************************** printf("Palindrome:%s ", line ); }else{ //To print to quoteOut.txt ******************* fprintf(fQuote, "%s ", line); //To print to screen ************************ printf("Quote:%s ", line ); line[0] = '\0'; } }
//To close my files *************************** fclose(fp); fclose(fPal); fclose(fQuote);
return 0;
}
void modtext(char line[]){
int i=0;
while(line[i]!='\0'){ if(line[i]>='A' && line[i]<='Z') line[i] = line[i]+32; i++; }
}
int isPalindrome(char line[]){ int i, j, k, len=0; k = i; while(line[len]!='\0') len++; for(i=0; i <= len; i++){ if(line[i]!=line[len-i-1]) return 0;
}
return 1;
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started