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中。

我心中的理想代碼如下:

 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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM