我试图编写一个程序,从阅读文件中找到一个单词并检查它是否是回文(来自两侧的同一个单词),如果是,则将它们保存到另一个文件中,并以返回方式分隔。阅读文件中的单词可以用任何方式书写:用空格,句子或返回来分隔。
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define MAX 255
int palindrome(char *x, int y, int i)
{
while(i<=y){
if(x[i]!=x[y])
return 0;
i++;y--;
}
return 1;
}
int main()
{
char *reading;
int length;
int x=0;
int y=0;
char read[MAX];
char write[MAX];
FILE *r;
FILE *w;
puts("Enter read file name");
scanf("%s", read);
puts("Enter write file name");
scanf("%s", write);
r=fopen(read, "r");
if(r==NULL)
perror("File does not exist");
w=fopen(write, "w");
reading=malloc(MAX*sizeof(char));
while(fgets(reading, MAX, r)!=NULL)
{
length=strlen(reading);
while(x<=length){
for(x=y; ;x++){
printf("%c\n", reading[x]);
if((reading[x]>='a'&& reading[x]<='z') || (reading[x]>='A' && reading[x]<='Z'))
break;
}
for(y=x; ;y++){
printf("%c\n",reading[y]);
if((reading[y]>='a'&& reading[y]<='z') || (reading[y]>='A' && reading[y]<='Z'));
else
break;
}
if(palindrome(reading, y, x)==1)
for( ;x<=y;x++)
fputc(reading[x], w);
x=y;
}
}
fclose(r);
fclose(w);
return 0;
}
问题是代码不起作用,如何解决?
答案 0 :(得分:0)
我发现您的代码中存在错误x
length=strlen(reading);
while(x<=length){
所以我对探测器的处理方式做了很多改动,而不是弄清楚你可能会破坏的其他限制。我已将输出写入stdout
而不是文件。请注意,我还在文件打开模式中添加了"t"
。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 255
int palindrome(char *string, int x, int y)
{
if (x >= y)
return 0;
while (y > x)
if (tolower(string[x++]) != tolower(string[--y]))
return 0;
return 1;
}
int main()
{
char reading[MAX+1];
char readfile[MAX+1];
int x, y, i;
FILE *r;
puts("Enter read file name");
scanf("%s", readfile);
r=fopen(readfile, "rt");
if(r==NULL)
perror("File does not exist");
else {
while (fgets (reading, MAX, r) != NULL) {
x = 0;
do {
while (reading[x] && !isalpha (reading[x]))
x++;
y = x;
while (isalpha (reading[y]))
y++;
if (palindrome (reading, x, y)) {
printf ("Palindrome: ");
for (i=x; i<y; i++)
printf ("%c", reading[i]);
printf ("\n");
}
x = y;
}
while (reading[x]);
}
fclose(r);
}
return 0;
}