Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

#include <stdio.h> #include <string.h> #include <stdlib.h> //Library needed for

ID: 3831579 • Letter: #

Question

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

//Library needed for exit(0)

int main()

{

int textFile;

FILE *fp;

fp = fopen("Proj3input.txt", "r");

if(fp == NULL)

{

printf("File does not exist. ");

exit(0);

}

while (fscanf (fp, "%d", &textFile) != EOF)

{

printf("%d ", textFile);

}

fclose(fp);

return 0;

}

This is what I have so far for my lab

A palindrome is a word or phrase that reads the same backwards and forwards, ignoring punctuation, spaces, and anything that isn’t a letter.

Examples of Palindromes

Madam, I’m Adam.

Kayak

Racecar

A man, a plan, a canal – Panama!

Able was I, ere I saw Elba.

Go hang a salami, I’m a lasagna hog.

Write a program that does the following:

1.opens a text file named “Proj3input.txt” containing multiple lines of text (1 or more)

2.for each line read from the text input file, print out “Palindrome:” followed by the line of text if itIS a palindrome, and print out “Not a palindrome:” followed by the line of text if it is NOT a palindrome.

while executing the program, create a file “Palindrome Results.txt” and mirror all your printouts to the screen into that file also.

This is for C

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// A function to check if a string str is palindrome
int isPalindrome(char str[])
{
// Start from leftmost and rightmost corners of str
int l = 0;
int h = strlen(str) - 1;
// Keep comparing characters while they are same
while (h > l)
{
if (str[l++] != str[h--])
{
return 0;
}
}
return 1;
}

int check_palindrome(char *line)
{
char text[1024];
int len = strlen(line);
int i, j = 0;
for(i = 0; i < len; i++)
{
if(isalpha(line[i]))
{
text[j++] = tolower(line[i]);
}
}
text[j] = '';
  
return isPalindrome(text);
}

int main(int argc, char *argv[]) {
int is_palindrome = 0;
int size = 1024, pos;
int c;
char *buffer = (char *)malloc(size);
  

FILE *f = fopen("Proj3input.txt", "r");
FILE *fp = fopen("Palindrome Results.txt", "w");
if(f) {
do { // read all lines in file
pos = 0;
do{ // read one line
c = fgetc(f);
if(c != EOF) buffer[pos++] = (char)c;
if(pos >= size - 1) { // increase buffer length - leave room for 0
size *=2;
buffer = (char*)realloc(buffer, size);
}
}while(c != EOF && c != ' ');
buffer[pos] = 0;
// line is now in buffer
is_palindrome = check_palindrome(buffer);
if(is_palindrome)
{
printf("%s", buffer);
fprintf(fp, "%s", buffer);
}
else
{
printf("Not a palindrome: %s", buffer);
fprintf(fp, "Not a palindrome: %s", buffer);
}
} while(c != EOF);
fclose(f);   
}
printf(" ");
fprintf(fp, " ");
fclose(fp);
free(buffer);
return 0;
}