【发布时间】:2015-12-06 14:34:25
【问题描述】:
这是我的输入函数:
int input( int array[500][500], int *x0, int *y0 ) {
int x = 0;
int y = 0;
int err = 0;
int temp = 0;
char c;
char s[2];
printf("Enter sizes:\n");
if (scanf("%d %d%c", x0, y0, &c) !=3 ||
*x0 <= 0 || *y0 <= 0 || *x0 > 500 || *y0 > 500 || c!='\n' ) {
printf("Invalid input.\n");
return 0;
}
while (y < *y0) {
x = 0;
temp = 0;
while ( x < *x0 ) {
if ( scanf("%1s", s)==1 ) {
c = *s;
} // so that ooo is written into three array fields
switch(c) { // only these three chars are accepted
case 'o':
array[y][x] = 1;
break;
case '.':
array[y][x] = 0;
break;
case '!':
array[y][x] = 2;
break;
default:
err = 1;
break;
}
x++;
temp = x;
if (temp > *x0) // my attempt
err = 1;
}
if (x != *x0)
err = 1;
y++;
}
if (y != *y0)
err = 1;
if (err == 1) {
printf("Invalid input.\n");
return 0;
}
return 1;
}
基本上,如果我输入:
3 3
oooo
ooo
ooo
它应该打印Invalid input.,因为第二个条目有 4 个字符而不是 3 个。同样,如果我写了 2 个字符而不是 3 个,它也应该打印错误消息。
我在尝试背后的想法是,在每次读取字符后,我将该字符写入数组(如果字符被接受),然后x++,这样我就可以将下一个输入写入下一个字段。因此,如果我有 4 个字符并且只应接受 3 个字符,x 将变为 4 并且 temp 也将变为 4。 4 > 3 所以err=1。
那么我的解决方案有什么问题?什么是正确的解决方案?提前致谢。
【问题讨论】:
-
哪部分逻辑不可见?首先我写 3 个数字,基本上是矩阵的大小。然后我写矩阵——只允许
o、!或.。如果我写的矩阵是 3x3 并且我输入了一个有 4 个字符的行,那当然是错误的,我需要能够发现这个错误。 -
scanf 不返回 1 时会发生什么
-
然后什么都没有。如果不是字符串,scanf 不会返回 1。即使它是一个字符串,我的开关也会说除非它是三个字符之一,否则我的错误标志会弹出。
-
你确定吗?检查你的逻辑
-
如果 scanf 失败(为什么你使用 %1s 是另一回事)你继续使用之前的 c 值