CyberArmy University | Open Source Institute | CyberArmy Intelligence & Security | CyberArmy Services & Projects

the C way


[Replies] [Reply] [View by Thread] [Help]
[Back To Programming]

Posted by Gamma Tr Chudik On 2008-08-10 18:31:49
In Reply to Programming challenge 3 -easy- Posted by Delta Cpt dopel On 2008-07-20 23:35:30

Gamma TrGamma Tr
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:


Guest:
Subject:
Message:
Signature:
Optional Image Link:
http://

CyberArmy::Forum v0.6
Generated In 0.00821 seconds


About Us | Privacy Policy | Mission Statement | Help