#include <stdio.h>
void w(char ch[][5],int x,int y){
ch[x][y]=' ';
}
void tart(char ch[][5],int x,int y){
ch[x][y]='0';
}
int main()
{
char cs[6][5] = {
{'#','#','#','#','#'},
{'#','0','#',' ','#'},
{'#',' ','#',' ','#'},
{'#',' ','#',' ','#'},
{'#','#',' ',' ','#'},
{'#','#','#',' ','#'}};
do{
int x,y;
x=1;
y=1;
char a;
scanf("%c",&a);
if(a=='w'){
w(cs,x,y);
tart(cs,x-1,y);
x--;
}
else if(a=='s'){
w(cs,x,y);
tart(cs,x+1,y);
y=y;
}
else if(a=='a'){
w(cs,x,y);
tart(cs,x,y-1);
y--;
}
else if(a=='d')
{
w(cs,x,y);
tart(cs,x,y+1);
y++;
}
for(int i=0;i<6;i++)
{
for(int j=0;j<5;j++)
{
printf("%c",cs[i][j]);
}
printf("\n");
}
}while(1);
}
初学者求大牛解惑,感谢!
缓冲区问题,你输入一个字符会回车,这时候缓冲区有两个字符,一个是你输入的,一个是回车,由于你do while循环把scanf括住了,所以会循环两次,输出两次
这个问题可能是因为在循环体内部有两处打印的原因,一处在do-while循环体内,另一处在循环体内的else if语句中。为了避免重复打印,可以将打印放在循环体外,或者在循环体内的else if语句中去掉打印。
输入语句输入缓冲区里多余字符的处理问题,第23行输入语句:scanf("%c",&a); 修改为:scanf(" %c",&a); 供参考:
#include <stdio.h>
void w(char ch[][5],int x,int y){
ch[x][y]=' ';
}
void tart(char ch[][5],int x,int y){
ch[x][y]='0';
}
int main()
{
char cs[6][5] = {
{'#','#','#','#','#'},
{'#','0','#',' ','#'},
{'#',' ','#',' ','#'},
{'#',' ','#',' ','#'},
{'#','#',' ',' ','#'},
{'#','#','#',' ','#'}};
do{
int x,y;
x=1;
y=1;
char a;
scanf(" %c",&a); //scanf("%c",&a); 修改
if(a=='w'){
w(cs,x,y);
tart(cs,x-1,y);
x--;
}
else if(a=='s'){
w(cs,x,y);
tart(cs,x+1,y);
y=y;
}
else if(a=='a'){
w(cs,x,y);
tart(cs,x,y-1);
y--;
}
else if(a=='d'){
w(cs,x,y);
tart(cs,x,y+1);
y++;
}
for(int i=0;i<6;i++)
{
for(int j=0;j<5;j++)
{
printf("%c",cs[i][j]);
}
printf("\n");
}
}while(1);
}