输入错误后继续循环

时间:2014-11-10 21:42:32

标签: c arrays input continue

#include<stdio.h>
#define M 6
#define N 5


int main(){

  int array[N][M];
  int i, j;

  for(i=0;i<N;i++){
    for(j=0;j<M;j++){
        scanf("%d", &array[i][j]);
        if(array[0][1]<1 || array[0][2]<1 || array[0][3]<1){
            // ??
        }

    }
  }
  return 0;
}

如何输入以使输入与我(很可能是错误的)if语句不匹配,如何         用户必须重新输入该数组字段,它不会跳到下一个输入字段吗?

2 个答案:

答案 0 :(得分:1)

  

如何输入以使输入与我(很可能是错误的)if语句不匹配,   用户必须重新输入该数组字段,它不会跳到下一个输入字段吗?

您可以让if语句的条件确定如何更新循环变量(用作数组索引):

for(i=0;i<N;i++){     // dont update i here
    for(j=0;j<M;j++){ // dont update j here

相反,如果您的条件满意,并且剩下任何行和列,则使用while循环更新ij

while(1) {
    printf("Enter value: ");
    scanf("%d", &array[i][j]);
    printf("array[%d][%d] = %d\n", i, j, array[i][j]);
    if(YOUR_CONDITION) {

        // update i and j inside this statement
        // this means the user can advance to the next array element
        // ONLY if your if statement condition is true

        if(j < M-1) { // if there are columns left, update j
            j++;
        }
        else if(i < N-1) { // otherwise, if there are rows left, reset j and update i
              j = 0; 
              i++; 
        } else {
            break;  // if we reach this point we are out of rows and columns and we break out of the loop
        } 
    } else {
          printf("Please satisfy the condition!\n");
    }
}

现在,就YOUR_CONDITION而言:

if(array[0][1]<1 || array[0][2]<1 || array[0][3]<1)

此声明的问题在于它正在检查数组中尚未由用户输入的值。

如果您指定要对此声明执行的操作,也许我可以提供进一步的帮助。

答案 1 :(得分:0)

要解决此问题,您可以简单地执行以下操作。如果输入错误,则将j递减1以强制用户重新输入相同的字段。告诉用户他们的输入错误也是有意义的,因此他们知道输入正确的值。