如何在嵌套的 for 循环中使用“继续一段时间”循环

How to use continue for a while loop in a nested for loop

本文关键字:循环 继续 一段时间 嵌套 for      更新时间:2023-10-16

但是,在满足 if 语句的条件后,我正在尝试继续 while 循环,但是,if 语句在 for 循环中,而继续语句只是继续 for 循环而不是 while 循环。我的代码如下所示:

while (valid_input == false) {
    printf("Enter a date (yyyy/mm/dd): ");
    fflush(stdout);
    fgets(date, 20, stdin);
    for (int i = 0; i <= 3; i++) {
        if (!isdigit(date[i])) {
            printf("Error: You didn't enter a date in the format (yyyy/mm/dd)n");
            continue;
        }
    }

我如何对此进行编码,以便在满足条件(!isdigit(date[i]((后继续在while循环的开头?

您可以

简单地使用另一个布尔变量来指示您要continue外部循环并break执行内部循环:

while (valid_input == false) {
    printf("Enter a date (yyyy/mm/dd): ");
    fflush(stdout);
    fgets(date, 20, stdin);
    bool continue_while = false; // <<<
    for (int i = 0; i <= 3; i++) {
        if (!isdigit(date[i])) {
            printf("Error: You didn't enter a date in the format (yyyy/mm/dd)n");
            continue_while = true; // <<<
            break; // <<< Stop the for loop
        }
    }
    if(continue_while) {
        continue; // continue the while loop and skip the following code
    }
    // Some more code in the while loop that should be skipped ...
}

如果没有更多需要跳过的代码,也许在 for() 循环中只break;就足够了。

使用

continue 是不可能的,您需要使用goto或条件。很难,在你的特定情况下,break会达到相同的结果。

顺便说一句。我在这里不考虑处理日期验证的设计决策。只需回答如何进行下一次while迭代。