#include <stdio.h>
#include<string.h>
main () {
FILE *fin = fopen ("beads.in", "r");
FILE *fout = fopen ("beads.out", "w");
int n;
char str[400];
char now,rev_now;
int pos,forward,reverse,sum,max=0,i,j,k;
fscanf(fin,"%d\n%s",&n,str);
n--;
for(pos=0;pos<=n;pos++){
now=str[pos];
if(pos==0)k=n;
else k=pos-1;
rev_now=str[k];
forward=2;
int flag1=0,flag2=0,reverse=2;
for(i=pos,j=k;;){
if(i==n)i=-1;
if((str[i+1]==now||str[i+1]=='w')&&flag1==0){
i++;
forward++;
}
else{
flag1=1;
}
if(j==0)j=n+1;
if((str[j-1]==rev_now||str[j-1]=='w')&&flag2==0){
j++;
reverse++;
}
else{
flag2=1;
}
if(flag1==1 && flag2==1)break;
}
sum=forward+reverse;
if(max<sum){max=sum;}
}
fprintf(fout,"%d\n",max);
return 0;
}
答案 0 :(得分:1)
您确定已beads.in
和beads.out
已创建..
根据手册页
r Open text file for reading. The stream is positioned at the
beginning of the file.
w Truncate file to zero length or create text file for writing.
The stream is positioned at the beginning of the file.
可能在fopen之前未创建beads.in
。最好检查fopen
的状态,使用perror
。
答案 1 :(得分:0)
您提到它适用于文本文件。我猜测beads.in
不是文本文件,而是二进制文件。如果是这种情况,那么@ KVD上面的建议使用:fopen ("beads.in", "rb");
和fopen ("beads.out", "wb");
应该有效。程序因二进制输入数据而崩溃的原因是因为您要求fscanf
将数据复制到str
缓冲区中,直到遇到换行符。很可能,beads.in
文件有超过400个字符,这将导致缓冲区溢出并开始覆盖程序堆栈。