找出文件中的回文

/*--------------------------------------------------------*/
/* This program looks at a character string and determines*/
/* if the string is a palindrome                          */

#include <fstream>
#include <cstring>
#include <cctype>
#include <iostream>
using namespace std;

bool is_palindrome(char string []);

const int BUFFERSIZE = 180;

void main(){
char buffer[BUFFERSIZE],new_string[BUFFERSIZE],filename[50];
int    count;
ifstream palindromes;

cout<<"Enter the name of the input file: ";
cin >>filename;
palindromes.open(filename);
if (palindromes.fail()) {
cout <<"error opening file" << filename << endl;
}
else{
//Input first line from file,process file
palindromes.getline(buffer,BUFFERSIZE);

//While not end of file,process string.
while (!palindromes.eof()) {
count = 0;
for(int k=0; k<strlen(buffer);k++){
if (isalnum(buffer[k])) {
new_string[count] = buffer[k];
count++;
}
}
//Assign null character to end of new_string.
new_string[count]='\0';

cout << buffer;
if (is_palindrome(new_string)) {
cout << "\tthis is a palindrome.\n";
}
else{
cout << "\tThis is not a palindrome.\n";
}
//Input next string.
palindromes.getline(buffer,BUFFERSIZE);
}
}
}

/*This function returns a value of true if string is a palindrome.*/
bool is_palindrome(char string []){
bool is_pal=true;
int begin(0),end;

end = strlen(string)-1;
while (is_pal&&begin<=end) {
if (string[begin]!=string[end]) {
is_pal = false;
}
begin++;
end--;
}
return(is_pal);
}

/*----------------------------------------------------------------*/

posted @ 2009-08-12 05:31  莫忆往西  阅读(165)  评论(0编辑  收藏  举报