UVA 227 Puzzle - 输入输出

时间:2023-03-09 04:49:01
UVA 227 Puzzle - 输入输出

题目:

acm.hust.edu.cn/vjudge/roblem/viewProblem.action?id=19191

这道题本身难度不大,但输入输出时需要特别小心,一不留神就会出问题。

对于输入,如果要读入一行时:

没有空白字符,则直接使用scanf和%s即可;

有空白字符,使用gets,但要小心溢出;fgets一直不能正常工作,有待研究(gets会将缓冲区多余的\n扔掉,fgets会保留在字符串中);

对于要读入单个字符时:

使用scanf和“ %c”进行舍弃空白字符(注意空格),并且最后需要getchar来吃掉最后的回车;

scanf和“%c”会读入空白字符,和getchar相同。

只忽略回车,不忽略空格时,可将getchar放在以c==‘\n'为循环条件的do while中。

我心中的理想代码如下:

 #include<stdio.h>
#include<string.h>
const int LEN=;
const int MAX=;
const int y[]={,,,-};
const int x[]={-,,,};
char map[LEN][LEN];
int tra[];
bool legal(int pos){
return <=pos&&pos<LEN;
}
void Pmap(){
for(int cow=;cow<LEN;cow++){
printf("%c",map[cow][]);
for(int col=;col<LEN;col++)
printf(" %c",map[cow][col]);
printf("\n");
}
}
int main(){
tra['A']=;
tra['B']=;
tra['R']=;
tra['L']=; bool first=true;
int Case=;
//freopen("in","r",stdin);
//freopen("out","w",stdout);
int bx,by;
while(gets(map[])){
if(map[][]=='Z')break;
for(int col=;col<LEN;col++)
gets(map[col]);
for(int i=;i<LEN;i++)
for(int j=;j<LEN;j++)
if(map[i][j]==' '){
bx=i;by=j;
}
bool ok=true;
char c;
while(scanf(" %c",&c),c!=''){
if(!ok)continue;
int nx=bx+x[tra[c]],ny=by+y[tra[c]];
if(!legal(nx)||!legal(ny)){
ok=false;
continue;
}
map[bx][by]=map[nx][ny];
map[nx][ny]=' ';
bx=nx;by=ny;
}
getchar();
if(first)
first=false;
else
printf("\n");
printf("Puzzle #%d:\n",++Case);
if(ok)
Pmap();
else
printf("This puzzle has no final configuration.\n");
}
return ;
}