【问题标题】:Continue after incorrect input for loop在for循环输入错误后继续
【发布时间】:2014-11-10 21:42:32
【问题描述】:
#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 语句不匹配,我该如何做到这一点,
用户必须重新输入该数组字段,它不只是跳到下一个输入字段?

【问题讨论】:

  • scanf放入while循环中,如果输入被验证,则while循环的条件设置为false。
  • 首先,您应该初始化您的数组,以便您的条件通过(memset 为 1 或其他值),否则您可能永远不会取得进展。然后你可以做类似printf("Invalid. Reenter.\n"); j--; continue;的事情。

标签: c arrays input continue


【解决方案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)

这个语句的问题在于它正在检查数组中尚未由用户输入的值。

如果你指定你想用这个语句做什么,也许我可以提供进一步的帮助。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 2016-07-01
      相关资源
      最近更新 更多