即时通讯新的C和不能为我的生活弄清楚我在这里做错了什么。第一个scanf工作正常,变量在读入时打印出来。第二个scanf似乎没有正确读取输入。输入格式为“char int int”,即当我打印opb x和y out,opb =“”,x = 13238272,y = 0时,输出格式为b 4 4
。 什么想法?.....注IVE切出代码的问题C scanf()问题
int main(void)
{
/*initialize variables*/
int width, height;
char op;
/*grid input*/
scanf("%c %d %d", &op, &width, &height);
/*check conditions*/
if (op != 'g' || width>100 || height>100 || width*height<10 || width<1 || height<1) {
printf("grid-error\n");
return 0;
}
/*initialize grid elements*/
int grid[width][height];
char printGrid[width][height];
/*create grid elements*/
int i, j;
for (i=0; i<height; i++) {
for (j=0; j<width; j++) {
grid[j][i] = 0;
printGrid[j][i] = '*';
}
}
/*print successful creation*/
printf("%c %d %d \n", op, width, height);
int k;
for (k = 0; k<10; k++) {
/*initialize variables*/
int x, y;
char opb;
/*mine input*/
scanf("%c %d %d", &opb, &x, &y);
/*check conditions*/
if (opb != 'b' || x<0 || y<0 || x>(width-1) || y>(height-1) || grid[x][y] == 9) {
printf("mine-error\n");
return 0;
}
您应该检查scanf函数的'()'的返回值,因为它是你就会知道,如果有一个格式错误的唯一方法。 – geekosaur 2011-03-23 06:04:17
你看起来是一个格式错误(因为它没有返回3),这是怎么回事? – Milk 2011-03-23 06:13:07
@ user445559:我发生的一件事情是,'%c'将读取下一个可用字符 - 即使它是空格或读取上一行时留下的换行符。一般来说,以行的形式读取输入并使用'sscanf()'来解析它们会更安全。 – geekosaur 2011-03-23 06:15:30