UVA 227 Puzzle - 输入输出

本文详细介绍了在ACM编程竞赛中,处理输入输出时的常见问题与解决方案,包括如何正确使用scanf、gets和fgets等函数,以及如何避免常见的错误,如缓冲区溢出和空白字符处理不当。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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 }

 

转载于:https://www.cnblogs.com/Beauty-Of-Code/p/4253896.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值