我试图在满足if语句的条件之后继续while循环,但if语句在for循环中,而continue语句只是继续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 ...
}
也许只有break;
循环中的for()
已经足够了,如果没有更多的代码需要被跳过。
使用continue
是不可能的,你需要使用goto
或条件。很难,在你的特殊情况下,break
会达到同样的效果。
顺便说一句。我不是在考虑设计决策来处理日期验证。只是回答如何进行下一个while
迭代。