the C way |
||
![]() ![]() Gamma Tr Chudik After intense efforts and a huge help in different forums - i have come up with this code. I have tried my best, please forgive me for the long code but I'm a noob in C. I think I'll take a decent break now from coding feewwwwwww.... :) #include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
bool isPalindrome(const char *str);
bool isPalindrome(const char *str)
{
size_t sLen = strlen(str);
if (sLen < 2)
return 0;
const char *ptr1 = str;
const char *ptr2 = str + sLen - 1;
const char *badChars = "!,?;.&-";
while((ptr1 < ptr2) && *ptr1)
{
if (isspace(*ptr1))
{
++ptr1;
continue;
}
if (strchr(badChars, *ptr1) != 0)
{
++ptr1;
continue;
}
if (isspace(*ptr2))
{
--ptr2;
continue;
}
if (strchr(badChars, *ptr2) != 0)
{
--ptr2;
continue;
}
if (tolower(*ptr1) != tolower(*ptr2))
return 0;
else
{
++ptr1;
--ptr2;
}
}
return 1;
}
int main()
{
FILE *file;
FILE *out;
char fname[50];
printf("Enter text file path to be checked for palindromes: \n");
scanf("%[^\n]", fname);
file = fopen(fname, "r");
if (file == NULL)
printf("Error: Cannot open file.\n");
else
printf("File Opened, checking for palindrome...\n");
char line[BUFSIZ];
out = fopen("output.txt", "a+");
while (fgets(line, sizeof line, file) != NULL)
{
if ( isPalindrome(line) )
fprintf( out, "%s\n", line);
}
fclose(file);
fclose(out);
return 0;
}
Chudik.
Replies:
|
||
| CyberArmy::Forum v0.6 Generated In 0.00821 seconds |