码迷,mamicode.com
首页 > 其他好文 > 详细

UVA 227 Puzzle - 输入输出

时间:2015-01-27 21:38:27      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

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

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

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

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

对于要读入单个字符时:

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

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

我心中的理想代码如下:

 1 #include<stdio.h>
 2 #include<string.h>
 3 const int LEN=5;
 4 const int MAX=100;
 5 const int y[]={0,0,1,-1};
 6 const int x[]={-1,1,0,0};
 7 char map[LEN][LEN];
 8 int tra[110];
 9 bool legal(int pos){
10     return 0<=pos&&pos<LEN;
11 }
12 void Pmap(){
13     for(int cow=0;cow<LEN;cow++){
14         printf("%c",map[cow][0]);
15         for(int col=1;col<LEN;col++)
16             printf(" %c",map[cow][col]);
17         printf("\n");
18     }
19 }
20 int main(){
21     tra[A]=0;
22     tra[B]=1;
23     tra[R]=2;
24     tra[L]=3;
25 
26     bool first=true;
27     int Case=0;
28     //freopen("in","r",stdin);
29     //freopen("out","w",stdout);
30     int bx,by;
31     while(gets(map[0])){
32         if(map[0][0]==Z)break;
33         for(int col=1;col<LEN;col++)
34             gets(map[col]);
35         for(int i=0;i<LEN;i++)
36             for(int j=0;j<LEN;j++)
37                 if(map[i][j]== ){
38                     bx=i;by=j;
39                 }
40         bool ok=true;
41         char c;
42         while(scanf(" %c",&c),c!=0){
43             if(!ok)continue;
44             int nx=bx+x[tra[c]],ny=by+y[tra[c]];
45             if(!legal(nx)||!legal(ny)){
46                 ok=false;
47                 continue;
48             }
49             map[bx][by]=map[nx][ny];
50             map[nx][ny]= ;
51             bx=nx;by=ny;
52         }
53         getchar();
54         if(first)
55             first=false;
56         else
57             printf("\n");
58         printf("Puzzle #%d:\n",++Case);
59         if(ok)
60             Pmap();
61         else
62             printf("This puzzle has no final configuration.\n");
63     }
64     return 0;
65 }

 

UVA 227 Puzzle - 输入输出

标签:

原文地址:http://www.cnblogs.com/Beauty-Of-Code/p/4253896.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!